import { HttpException, HttpStatus } from '@nestjs/common';

/**
 * 业务异常基类
 * 
 * 用于抛出业务相关的异常，会被全局异常过滤器捕获并格式化
 * 
 * 使用方式：
 * throw new BusinessException('用户不存在', 'USER_NOT_FOUND', HttpStatus.NOT_FOUND);
 * 
 * 或继承此类创建具体的业务异常：
 * class UserNotFoundException extends BusinessException {
 *   constructor(userId: string) {
 *     super(`用户 ${userId} 不存在`, 'USER_NOT_FOUND', HttpStatus.NOT_FOUND);
 *   }
 * }
 */
export class BusinessException extends HttpException {
  constructor(
    message: string,
    code: string = 'BUSINESS_ERROR',
    statusCode: HttpStatus = HttpStatus.BAD_REQUEST,
    details?: any,
  ) {
    super(
      {
        error: code,
        code: code, // 兼容两种格式
        message,
        details,
      },
      statusCode,
    );
  }
}

// ==================== 用户相关异常 ====================

/**
 * 用户不存在异常
 */
export class UserNotFoundException extends BusinessException {
  constructor(userId?: string) {
    super(
      userId ? `用户 ${userId} 不存在` : '用户不存在',
      'USER_NOT_FOUND',
      HttpStatus.NOT_FOUND,
    );
  }
}

/**
 * 用户已存在异常
 */
export class UserAlreadyExistsException extends BusinessException {
  constructor(identifier: string) {
    super(
      `用户 ${identifier} 已存在`,
      'USER_ALREADY_EXISTS',
      HttpStatus.CONFLICT,
    );
  }
}

/**
 * 无效凭证异常（用户名或密码错误）
 */
export class InvalidCredentialsException extends BusinessException {
  constructor() {
    super('用户名或密码错误', 'INVALID_CREDENTIALS', HttpStatus.UNAUTHORIZED);
  }
}

/**
 * 密码强度不足异常
 */
export class PasswordTooWeakException extends BusinessException {
  constructor(requirements?: string[]) {
    super(
      '密码强度不足',
      'PASSWORD_TOO_WEAK',
      HttpStatus.BAD_REQUEST,
      requirements
        ? { requirements }
        : { requirements: ['8位以上', '包含大小写字母', '包含数字'] },
    );
  }
}

/**
 * 邮箱已被使用异常
 */
export class EmailAlreadyTakenException extends BusinessException {
  constructor(email: string) {
    super(
      `邮箱 ${email} 已被使用`,
      'EMAIL_ALREADY_TAKEN',
      HttpStatus.CONFLICT,
    );
  }
}

// ==================== 角色和权限相关异常 ====================

/**
 * 角色不存在异常
 */
export class RoleNotFoundException extends BusinessException {
  constructor(roleId?: string) {
    super(
      roleId ? `角色 ${roleId} 不存在` : '角色不存在',
      'ROLE_NOT_FOUND',
      HttpStatus.NOT_FOUND,
    );
  }
}

/**
 * 权限不足异常
 */
export class InsufficientPermissionsException extends BusinessException {
  constructor(permission?: string) {
    super(
      permission ? `需要权限: ${permission}` : '权限不足',
      'INSUFFICIENT_PERMISSIONS',
      HttpStatus.FORBIDDEN,
      { requiredPermission: permission },
    );
  }
}

/**
 * 无法删除内置角色异常
 */
export class CannotDeleteBuiltInRoleException extends BusinessException {
  constructor(roleName: string) {
    super(
      `内置角色 ${roleName} 无法删除`,
      'CANNOT_DELETE_BUILTIN_ROLE',
      HttpStatus.FORBIDDEN,
    );
  }
}

// ==================== 部门和职位相关异常 ====================

/**
 * 部门不存在异常
 */
export class DepartmentNotFoundException extends BusinessException {
  constructor(departmentId?: string) {
    super(
      departmentId ? `部门 ${departmentId} 不存在` : '部门不存在',
      'DEPARTMENT_NOT_FOUND',
      HttpStatus.NOT_FOUND,
    );
  }
}

/**
 * 职位不存在异常
 */
export class PositionNotFoundException extends BusinessException {
  constructor(positionId?: string) {
    super(
      positionId ? `职位 ${positionId} 不存在` : '职位不存在',
      'POSITION_NOT_FOUND',
      HttpStatus.NOT_FOUND,
    );
  }
}

// ==================== LDAP 相关异常 ====================

/**
 * LDAP 同步失败异常
 */
export class LdapSyncFailedException extends BusinessException {
  constructor(reason?: string) {
    super(
      reason ? `LDAP 同步失败: ${reason}` : 'LDAP 同步失败',
      'LDAP_SYNC_FAILED',
      HttpStatus.BAD_REQUEST,
    );
  }
}

/**
 * LDAP 连接失败异常
 */
export class LdapConnectionFailedException extends BusinessException {
  constructor(reason?: string) {
    super(
      reason ? `LDAP 连接失败: ${reason}` : 'LDAP 连接失败',
      'LDAP_CONNECTION_FAILED',
      HttpStatus.SERVICE_UNAVAILABLE,
    );
  }
}

// ==================== 文件相关异常 ====================

/**
 * 文件过大异常
 */
export class FileTooLargeException extends BusinessException {
  constructor(maxSize?: string) {
    super(
      maxSize ? `文件大小超过限制 (最大 ${maxSize})` : '文件过大',
      'FILE_TOO_LARGE',
      HttpStatus.BAD_REQUEST,
      { maxSize },
    );
  }
}

/**
 * 文件类型不正确异常
 */
export class InvalidFileTypeException extends BusinessException {
  constructor(allowedTypes?: string[]) {
    super(
      allowedTypes
        ? `文件类型不正确，允许的类型: ${allowedTypes.join(', ')}`
        : '文件类型不正确',
      'INVALID_FILE_TYPE',
      HttpStatus.BAD_REQUEST,
      { allowedTypes },
    );
  }
}

// ==================== 资源相关异常 ====================

/**
 * 资源不存在异常
 */
export class ResourceNotFoundException extends BusinessException {
  constructor(resource: string, id?: string) {
    super(
      id ? `${resource} ${id} 不存在` : `${resource} 不存在`,
      'RESOURCE_NOT_FOUND',
      HttpStatus.NOT_FOUND,
    );
  }
}

/**
 * 资源已存在异常
 */
export class ResourceAlreadyExistsException extends BusinessException {
  constructor(resource: string, identifier?: string) {
    super(
      identifier ? `${resource} ${identifier} 已存在` : `${resource} 已存在`,
      'RESOURCE_ALREADY_EXISTS',
      HttpStatus.CONFLICT,
    );
  }
}

/**
 * 资源冲突异常
 */
export class ResourceConflictException extends BusinessException {
  constructor(message: string, details?: any) {
    super(message, 'RESOURCE_CONFLICT', HttpStatus.CONFLICT, details);
  }
}

// ==================== Token 相关异常 ====================

/**
 * Token 已过期异常
 */
export class TokenExpiredException extends BusinessException {
  constructor() {
    super('Token 已过期，请重新登录', 'TOKEN_EXPIRED', HttpStatus.UNAUTHORIZED);
  }
}

/**
 * Token 无效异常
 */
export class InvalidTokenException extends BusinessException {
  constructor() {
    super('Token 无效', 'INVALID_TOKEN', HttpStatus.UNAUTHORIZED);
  }
}

