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

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

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

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = 'Internal server error';
    let error = 'Internal Server Error';

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const responseContent = exception.getResponse();
      if (typeof responseContent === 'string') {
        message = responseContent;
      } else if (typeof responseContent === 'object' && responseContent !== null) {
        const resp = responseContent as any;
        message = resp.message || resp.error || message;
        error = resp.error || error;
      }
    } else if (exception instanceof Error) {
      message = exception.message;
      this.logger.error(`Unhandled exception: ${exception.stack}`);
    }

    const requestId = (request.headers['x-request-id'] as string) || 'unknown';

    response.status(status).json({
      success: false,
      error: {
        code: status,
        message,
        details: error,
      },
      requestId,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}