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

@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();

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

    const messageRaw =
      exception instanceof HttpException
        ? exception.getResponse()
        : '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),
      );
      console.error('Full error details:', exception);
    } else {
      this.logger.warn(`${request.method} ${request.url} -> ${status} ${message}`);
    }

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