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

/**
 * Global HTTP exception filter.
 *
 * Normalizes the error envelope to:
 * ```json
 * {
 *   "statusCode": 400,
 *   "message": "...",
 *   "error": "...",
 *   "timestamp": "ISO-8601",
 *   "path": "..."
 * }
 * ```
 */
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status =
      exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    // Malformed bigint/number inputs (e.g. `BigInt("abc")`) are client
    // errors — map them to 400 instead of leaking a 500.
    if (
      status === HttpStatus.INTERNAL_SERVER_ERROR &&
      exception instanceof Error &&
      /Cannot convert .+ to (a BigInt|number)/i.test(exception.message)
    ) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        message: 'Invalid numeric identifier',
        error: 'BadRequestError',
        timestamp: new Date().toISOString(),
        path: request.url,
      });
      return;
    }

    let message: string | string[] = 'Internal server error';
    let error = 'InternalServerError';

    if (exception instanceof HttpException) {
      const resp = exception.getResponse();
      if (typeof resp === 'string') {
        message = resp;
      } else if (typeof resp === 'object' && resp !== null) {
        const obj = resp as Record<string, unknown>;
        message = (obj.message as string | string[]) ?? exception.message;
        error = (obj.error as string) ?? exception.name;
      } else {
        message = exception.message;
      }
    } else if (exception instanceof Error) {
      // Unexpected errors (Prisma, driver, ...) may contain SQL or
      // connection details — never send them to the client.
      this.logger.error(
        `${request.method} ${request.url} -> ${status} ${exception.message}`,
        exception.stack,
      );
    }

    if (status >= 500 && exception instanceof HttpException) {
      this.logger.error(
        `${request.method} ${request.url} -> ${status} ${message}`,
        exception instanceof Error ? exception.stack : undefined,
      );
    }

    response.status(status).json({
      statusCode: status,
      message,
      error,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
