import { Socket } from 'socket.io';
import { UserService } from '@/server/modules/users/user.service';
import { AppDataSource } from '@/server/data-source';
import debug from 'debug';
import { UserEntity } from '@/server/modules/users/user.entity';
import { AuthService } from '@/server/modules/auth/auth.service';

const log = debug('socket:auth');

export interface AuthenticatedSocket extends Socket {
  user?: UserEntity;
}

export const createSocketAuthMiddleware = () => {
  return async (socket: AuthenticatedSocket, next: (err?: Error) => void) => {
    try {
      // 获取 token
      const token = socket.handshake.auth?.token || socket.handshake.query?.socket_token;
      
      if (!token) {
        log('未提供token，拒绝连接');
        return next(new Error('未授权'));
      }

      // 使用 AuthService 统一验证 token - 与 HTTP API 保持一致
      const userService = new UserService(AppDataSource);
      const authService = new AuthService(userService);
      const decoded = authService.verifyToken(token as string);

      // 获取用户信息
      const user = await userService.getUserById(decoded.id);

      if (!user) {
        log('无效用户，拒绝连接');
        return next(new Error('无效凭证'));
      }

      // 检查用户状态
      if (user.isDisabled === 1) {
        log('用户被禁用，拒绝连接');
        return next(new Error('用户被禁用'));
      }

      if (user.isDeleted === 1) {
        log('用户已删除，拒绝连接');
        return next(new Error('用户不存在'));
      }

      // 设置用户信息到 socket
      socket.user = user;
      
      log(`用户认证成功: ${user.username} (ID: ${user.id})`);
      next();
    } catch (error) {
      log('认证错误:', error);
      
      const err = error as Error;
      if (err.name === 'JsonWebTokenError' || err.name === 'TokenExpiredError') {
        return next(new Error('无效的token'));
      }
      
      next(new Error('认证失败'));
    }
  };
};