import { GenerateKeysService } from '@/modules/admins/services/generate-key.service';
import { clientGetWayMiddleware } from '@/modules/auth/middlewares/client-get-way.middleware copy';
import { EventEmitter2 } from '@nestjs/event-emitter';
import {
  OnGatewayConnection,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { BidsService } from '../services/bids.service';
import { WebBidsService } from '../services/web-bids.service';
import { Event } from '../utils/events';
import { WebBid } from '../entities/wed-bid.entity';

@WebSocketGateway({
  namespace: 'bid-ws',
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
    credentials: true,
  },
})
export class BidGateway implements OnGatewayConnection {
  @WebSocketServer()
  server: Server;

  constructor(
    private eventEmitter: EventEmitter2,
    private webBidsService: WebBidsService,
    private generateKeysService: GenerateKeysService,
  ) {}

  async onModuleInit() {
    this.eventEmitter.on(Event.BIDS_UPDATED, (data) => {
      this.server.emit(Event.BIDS_UPDATED, data);
    });

    this.eventEmitter.on(Event.WEB_UPDATED, (data) => {
      this.server.emit(Event.WEB_UPDATED, data);
    });

    this.eventEmitter.onAny(
      (
        event: string,
        payload: { name: string; code: string; web_bid: WebBid },
      ) => {
        if (!event.startsWith(Event.VERIFY_CODE)) return;

        this.server.emit(Event.verifyCode(payload.web_bid), payload);
      },
    );
  }

  async handleConnection(client: Socket) {
    await clientGetWayMiddleware(client, this.generateKeysService);

    console.log(`📢 Client connected: ${client.id}`);

    const data = await this.webBidsService.getDataClient();
    // Gửi dữ liệu bids ngay khi client kết nối
    client.emit(Event.BIDS_UPDATED, data);
  }
}
