import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';

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

  catch(exception: unknown, host: ArgumentsHost): void {
    // Global filter — also reached by non-HTTP (e.g. RabbitMQ) handlers. switchToHttp() would
    // yield no response object there, so re-throw and let the transport (golevelup) handle it
    // (nack/dead-letter) instead of crashing on response.status().
    if (host.getType() !== 'http') {
      throw exception;
    }
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    let prismaMessage: string | null = null;
    let prismaCode: string | null = null;
    let prismaMeta: unknown = null;
    if (exception instanceof PrismaClientKnownRequestError) {
      prismaCode = exception.code;
      prismaMeta = exception.meta;
      if (exception.code === 'P2003') {
        const field = (exception.meta?.field_name as string | undefined) ?? 'a related record';
        prismaMessage = `Cannot delete this record because it is still referenced by ${field}. Remove the related records first.`;
      } else if (exception.code === 'P2025') {
        prismaMessage = 'Record not found.';
      }
    }

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

    const messageRaw =
      exception instanceof HttpException
        ? exception.getResponse()
        : prismaMessage ?? 'Internal server error';

    const message =
      typeof messageRaw === 'string'
        ? messageRaw
        : ((messageRaw as { message?: string }).message ?? 'Unexpected error');

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

    // When the thrown body is already a structured object (e.g. { status, message, code }),
    // merge it into the envelope so callers receive all custom fields.
    const customFields =
      typeof messageRaw === 'object' && messageRaw !== null ? messageRaw : {};

    response.status(status).json({
      success: false,
      statusCode: status,
      message,
      error: exception instanceof Error ? exception.name : 'Error',
      ...(prismaCode ? { prismaCode, prismaMeta } : {}),
      timestamp: new Date().toISOString(),
      path: request.url,
      ...customFields,
    });
  }
}
