import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request, Response } from 'express';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(GlobalExceptionFilter.name);

  constructor(private readonly configService: ConfigService) {}

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const isProduction =
      this.configService.get<string>('app.nodeEnv') === 'production';

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = '服务器内部错误';
    let errorCode: string | undefined;

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
        const resp = exceptionResponse as Record<string, unknown>;
        errorCode = resp['errorCode'] as string | undefined;
        message =
          (resp['message'] as string) || exception.message;
      } else {
        message = String(exceptionResponse);
      }

      if (Array.isArray(message)) message = message.join('; ');
    }

    if (status >= 500) {
      this.logger.error(
        `[${request.method}] ${request.url} -> ${status}: ${message}`,
        isProduction ? undefined : (exception as any)?.stack,
      );
    }

    response.status(status).json({
      success: false,
      statusCode: status,
      message,
      ...(errorCode ? { errorCode } : {}),
      ...(isProduction ? {} : { path: request.url }),
    });
  }
}
