import { JwtService, TokenExpiredError } from '@nestjs/jwt';
import { AdminsService } from '@/modules/admins/services/admins.service';
import * as cookie from 'cookie';
import { Socket } from 'socket.io';
import { plainToClass } from 'class-transformer';
import Admin from '@/modules/admins/entities/admin.entity';

export async function getWayMiddleware(
  client: Socket,
  jwtService: JwtService,
  adminService: AdminsService,
): Promise<void> {
  try {
    const cookies = cookie.parse(client.handshake.headers.cookie || '');
    const accessToken = cookies['access_token'];
    const refreshToken = cookies['refresh_token'];

    if (!accessToken && !refreshToken) {
      console.log('🚫 No tokens provided, disconnecting WebSocket');
      client.disconnect();
      return;
    }

    let admin: Admin | null = null;

    try {
      const result = await jwtService.verify(accessToken);

      if (!result?._id || result.refresh_key) {
        throw new Error('Invalid access token');
      }

      admin = await adminService.adminRepo.findOne({
        where: { id: result._id },
      });

      if (!admin) throw new Error('Admin not found');
    } catch (error) {
      console.log('❗ Invalid access token, disconnecting WebSocket');
      client.disconnect();
      return;
    }

    client.data.admin = plainToClass(Admin, admin);
    console.log(`✅ WebSocket authenticated: Admin ID ${admin.id}`);
  } catch (error) {
    console.log('❌ WebSocket authentication error:', error);
    client.disconnect();
  }
}
