import { type ArgumentsHost, Catch, type ExceptionFilter, type HttpException, HttpStatus } from '@nestjs/common';
import type { FastifyReply } from 'fastify';
import { CustomException } from '../exceptions/custom.exception';
import type { LoggerService } from '../../plugins/logger/logger.service';

/**
 * 异常捕获过滤器.
 */
@Catch()
export class CatchExceptionFilter implements ExceptionFilter {
  public constructor(private readonly logger: LoggerService) {}

  /**
   * 重写 catch 方法，实现自定义的异常捕获逻辑.
   */
  public catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();

    /**
     * 获取 Fastify 响应对象
     */
    const response = ctx.getResponse<FastifyReply>();

    const errorResponse = {
      code: exception?.getStatus?.() || HttpStatus.INTERNAL_SERVER_ERROR,
      msg: exception.message,
      data: null,
    };

    if (exception instanceof CustomException) {
      errorResponse.msg = exception.message;
    } else if (exception.message.includes('Body cannot be empty when content-type is')) {
      errorResponse.msg = 'body不能为空';
    } else {
      // 打印日志
      errorResponse.code !== 401 && this.logger.error(exception);
      // 判断不同的异常类型并设置中文提示信息
      switch (errorResponse.code) {
        case 400:
          // BadRequestException 异常
          errorResponse.msg = '请求格式错误';
          break;
        case 401:
          console.log('exception====', exception);
          // UnauthorizedException 异常
          errorResponse.msg = '未授权访问';
          break;
        case 403:
          // ForbiddenException 异常
          errorResponse.msg = '没有权限';
          break;
        case 404:
          // NotFoundException 异常
          errorResponse.msg = '资源未找到';
          break;
        case 406:
          // NotAcceptableException 异常
          errorResponse.msg = '请求的格式不被接受';
          break;
        case 408:
          // RequestTimeoutException 异常
          errorResponse.msg = '请求超时';
          break;
        case 409:
          // ConflictException 异常
          errorResponse.msg = '请求冲突';
          break;
        case 410:
          // GoneException 异常
          errorResponse.msg = '资源已不存在';
          break;
        case 413:
          // PayloadTooLargeException 异常
          errorResponse.msg = '请求负载过大';
          break;
        case 415:
          // UnsupportedMediaTypeException 异常
          errorResponse.msg = '不支持的媒体类型';
          break;
        case 422:
          // UnprocessableException 异常
          errorResponse.msg = '参数错误';
          break;
        case 423:
          errorResponse.msg = '参数错误';
          break;
        case 500:
          // InternalServerErrorException 异常
          errorResponse.msg = '服务器内部错误';
          break;
        case 501:
          // NotImplementedException 异常
          errorResponse.msg = '功能尚未实现';
          break;
        case 502:
          // BadGatewayException 异常
          errorResponse.msg = '错误的网关';
          break;
        case 503:
          // ServiceUnavailableException 异常
          errorResponse.msg = '服务不可用';
          break;
        case 504:
          // GatewayTimeoutException 异常
          errorResponse.msg = '网关超时';
          break;
        default:
          errorResponse.msg = '内部服务器错误,001';
          break;
      }
    }

    response.status(HttpStatus.OK).send(errorResponse);
  }
}
