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

/**
 * Global exception filter implementing RFC 7807 Problem Details.
 * All errors are returned in a consistent format.
 */
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger('ExceptionFilter');

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

    let status: number;
    let message: string = 'Unknown error';
    let details: any;

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exResponse = exception.getResponse();
      if (typeof exResponse === 'string') {
        message = exResponse;
      } else if (typeof exResponse === 'object') {
        message = (exResponse as any).message || exception.message;
        details = (exResponse as any).errors || (exResponse as any).details;
      }
    } else if (exception instanceof Error) {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      message = 'Internal server error';
      this.logger.error(
        `Unhandled error: ${exception.message}`,
        exception.stack,
      );
    } else {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      message = 'Unknown error';
    }

    // RFC 7807 Problem Details format
    const problemDetails = {
      type: `https://api.gogenex.com/errors/${status}`,
      title: HttpStatus[status] || 'Error',
      status,
      detail: Array.isArray(message) ? message.join('; ') : message,
      instance: request.url,
      timestamp: new Date().toISOString(),
      ...(details && { errors: details }),
    };

    response.status(status).json(problemDetails);
  }
}
