import { AdminsService } from '@/modules/admins/services/admins.service';
import { getWayMiddleware } from '@/modules/auth/middlewares/get-way.middleware';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { JwtService } from '@nestjs/jwt';
import {
  OnGatewayConnection,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { plainToClass } from 'class-transformer';
import { Server, Socket } from 'socket.io';
import { WebBid } from '../entities/wed-bid.entity';
import { WebBidsService } from '../services/web-bids.service';
import * as Imap from 'imap';
import { ImapService } from '../services/mail/imap.service';
import { ConfigService } from '@nestjs/config';
import { Event } from '../utils/events';

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

  constructor(
    private eventEmitter: EventEmitter2,
    private readonly jwtService: JwtService,
    private webBidsService: WebBidsService,
    private readonly adminService: AdminsService,
    private readonly imapService: ImapService,
  ) {
    this.imapService.server = this.server;
  }

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

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

    this.eventEmitter.onAny(
      (
        event: string,
        payload: { login_status: string; data: WebBid },
      ) => {
        if (!event.startsWith(Event.LOGIN_STATUS)) return;

        this.server.emit(Event.statusLogin(payload.data), payload);
      },
    );

    // IMAP
    this.imapService.connectIMAP();
  }

  async handleConnection(client: Socket) {
    await getWayMiddleware(client, this.jwtService, this.adminService);

    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.ADMIN_BIDS_UPDATED, plainToClass(WebBid, data));
  }
}
