import debug from 'debug';
import { JWTService, JWTPayload } from './jwt.service.js';
import { EnableStatus } from '@d8d/shared-types';

const logger = {
  info: debug('auth-core:auth:info'),
  error: debug('auth-core:auth:error')
}

export interface User {
  id: number;
  username: string;
  nickname?: string;
  isDisabled: EnableStatus;
  roles?: Array<{ name: string }>;
  openid?: string;
}

export interface UserService {
  getUserByUsername(username: string): Promise<User | null>;
  verifyPassword(user: User, password: string): Promise<boolean>;
  createUser(userData: Partial<User> & { username: string; password: string }): Promise<User>;
}

export class AuthService {
  private userService: UserService;

  constructor(userService: UserService) {
    this.userService = userService;
  }

  async login(username: string, password: string): Promise<{ token: string; user: User }> {
    try {
      const user = await this.userService.getUserByUsername(username);
      if (!user) {
        throw new Error('用户不存在');
      }

      // 检查用户是否被禁用
      if (user.isDisabled === EnableStatus.DISABLED) {
        throw new Error('用户账户已被禁用');
      }

      const isPasswordValid = await this.userService.verifyPassword(user, password);
      if (!isPasswordValid) {
        throw new Error('密码错误');
      }

      const payload: JWTPayload = {
        id: user.id,
        username: user.username,
        roles: user.roles?.map(role => role.name) || [],
        openid: user.openid || undefined
      };

      const token = JWTService.generateToken(payload);
      return { token, user };
    } catch (error) {
      logger.error('登录错误:', error);
      throw error;
    }
  }

  generateToken(user: User, expiresIn?: string): string {
    const payload: JWTPayload = {
      id: user.id,
      username: user.username,
      roles: user.roles?.map(role => role.name) || [],
      openid: user.openid || undefined
    };
    return JWTService.generateToken(payload, expiresIn);
  }

  verifyToken(token: string): JWTPayload {
    return JWTService.verifyToken(token);
  }

  async logout(token: string): Promise<void> {
    try {
      // 验证token有效性
      const decoded = this.verifyToken(token);
      if (!decoded) {
        throw new Error('无效的token');
      }

      // 实际项目中这里可以添加token黑名单逻辑
      // 或者调用Redis等缓存服务使token失效

      return Promise.resolve();
    } catch (error) {
      logger.error('登出失败:', error);
      throw error;
    }
  }

  /**
   * 验证用户权限
   * @param user 用户信息
   * @param requiredRole 需要的角色
   * @returns 是否有权限
   */
  hasPermission(user: User, requiredRole: string): boolean {
    return user.roles?.some(role => role.name === requiredRole) || false;
  }

  /**
   * 验证用户是否有任意一个权限
   * @param user 用户信息
   * @param requiredRoles 需要的角色列表
   * @returns 是否有权限
   */
  hasAnyPermission(user: User, requiredRoles: string[]): boolean {
    return requiredRoles.some(role => this.hasPermission(user, role));
  }
}