import jwt from 'jsonwebtoken';
import { UserService } from '../users/user.service';
import { UserEntity as User } from '../users/user.entity';
import { DisabledStatus } from '@/share/types';
import debug from 'debug';

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

const JWT_SECRET = 'your-secret-key'; // 生产环境应使用环境变量
const JWT_EXPIRES_IN = '7d'; // 7天有效期
const ADMIN_USERNAME = 'admin';
const ADMIN_PASSWORD = 'admin123';

export class AuthService {
  private userService: UserService;

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

  async ensureAdminExists(): Promise<User> {
    try {
      let admin = await this.userService.getUserByUsername(ADMIN_USERNAME);
      if (!admin) {
        logger.info('Admin user not found, creating default admin account');
        admin = await this.userService.createUser({
          username: ADMIN_USERNAME,
          password: ADMIN_PASSWORD,
          nickname: '系统管理员',
          isDisabled: DisabledStatus.ENABLED
        });
        logger.info('Default admin account created successfully');
      }
      return admin;
    } catch (error) {
      logger.error('Failed to ensure admin account exists:', error);
      throw error;
    }
  }

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

      // 检查用户是否被禁用
      if (user.isDisabled === DisabledStatus.DISABLED) {
        throw new Error('User account is disabled');
      }

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

      const token = this.generateToken(user);
      return { token, user };
    } catch (error) {
      logger.error('Login error:', error);
      throw error;
    }
  }

  generateToken(user: User, expiresIn?: string | number): string {
    const payload = {
      id: user.id,
      username: user.username,
      roles: user.roles?.map(role => role.name) || []
    };
    const options = expiresIn ? { expiresIn } : { expiresIn: JWT_EXPIRES_IN };
    return jwt.sign(payload, JWT_SECRET, options as jwt.SignOptions);
  }

  verifyToken(token: string): any {
    try {
      return jwt.verify(token, JWT_SECRET);
    } catch (error) {
      console.error('Token verification failed:', error);
      throw new Error('Invalid token');
    }
  }

  async logout(token: string): Promise<void> {
    try {
      // 验证token有效性
      const decoded = this.verifyToken(token);
      if (!decoded) {
        throw new Error('Invalid token');
      }
      
      // 实际项目中这里可以添加token黑名单逻辑
      // 或者调用Redis等缓存服务使token失效
      
      return Promise.resolve();
    } catch (error) {
      console.error('Logout failed:', error);
      throw error;
    }
  }
}