import { UserService } from '@d8d/core-module/user-module';
import { DisabledStatus } from '@d8d/shared-types';
import { JWTUtil } from '@d8d/shared-utils';
import debug from 'debug';

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

const ADMIN_USERNAME = 'admin';
const ADMIN_PASSWORD = 'admin123';

export class AuthService {
  private userService: UserService;

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

  async ensureAdminExists(): Promise<any> {
    try {
      let admin = await this.userService.getUserByUsername(ADMIN_USERNAME);
      if (!admin) {
        logger.info('Admin user not found, creating default admin account');
        const adminData: any = {
          username: ADMIN_USERNAME,
          password: ADMIN_PASSWORD,
          nickname: '系统管理员',
          isDisabled: DisabledStatus.ENABLED
        };

        admin = await this.userService.createUser(adminData);
        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: any }> {
    try {
      // 确保admin用户存在
      if (username === ADMIN_USERNAME) {
        await this.ensureAdminExists();
      }

      const user = await this.userService.getUserByUsername(username);
      if (!user) {
        throw new Error('用户不存在');
      }

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

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

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

  generateToken(user: any, expiresIn?: string): string {
    const tokenPayload = {
      ...user
    };
    return JWTUtil.generateToken(tokenPayload, {}, expiresIn);
  }

  verifyToken(token: string): any {
    return JWTUtil.verifyToken(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;
    }
  }

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

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

      // 验证用户是否是企业用户（company_id不为空）
      if (!user.companyId) {
        throw new Error('用户不是企业用户');
      }

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

      // 加载企业关联信息
      const userWithCompany = await this.userService.getUserWithCompany(user.id);

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

  async verifyEnterpriseUser(userId: number): Promise<boolean> {
    try {
      const user = await this.userService.getUserById(userId);
      if (!user) {
        return false;
      }
      return !!user.companyId;
    } catch (error) {
      logger.error('Verify enterprise user error:', error);
      return false;
    }
  }
}