import {
  WebSocketGateway,
  WebSocketServer,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger, Injectable } from '@nestjs/common';

export interface PriceUpdate {
  price: string;
  burnMultiplier: string;
  timestamp: number;
}

@Injectable()
@WebSocketGateway({
  namespace: '/price',
  cors: {
    origin: '*',
    credentials: true,
  },
  transports: ['websocket', 'polling'],
})
export class PriceGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer()
  server: Server;

  private readonly logger = new Logger(PriceGateway.name);
  private connectedClients = 0;

  afterInit() {
    this.logger.log('🚀 Price WebSocket Gateway initialized');
    this.logger.log(`📡 Namespace: /price`);
    this.logger.log(`🔧 Transports: websocket, polling`);
  }

  handleConnection(client: Socket) {
    this.connectedClients++;
    this.logger.log(
      `✅ Client connected: ${client.id}, IP: ${client.handshake.address}, total: ${this.connectedClients}`,
    );
    this.logger.debug(`📋 Handshake headers: ${JSON.stringify(client.handshake.headers)}`);
  }

  handleDisconnect(client: Socket) {
    this.connectedClients--;
    this.logger.log(
      `❌ Client disconnected: ${client.id}, total: ${this.connectedClients}`,
    );
  }

  /**
   * 广播价格更新到所有连接的客户端
   */
  broadcastPriceUpdate(priceUpdate: PriceUpdate): void {
    if (this.server && this.connectedClients > 0) {
      this.server.emit('priceUpdate', priceUpdate);
      this.logger.log(
        `📊 Price broadcast to ${this.connectedClients} clients: price=${priceUpdate.price}, burnMultiplier=${priceUpdate.burnMultiplier}`,
      );
    }
  }

  /**
   * 获取当前连接数
   */
  getConnectedClientsCount(): number {
    return this.connectedClients;
  }
}
