import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus, Logger } from '@nestjs/common';
import { Response } from 'express';
import { ERROR_CODES } from '@common/constants/error-codes';

interface ErrorResponse {
  success: boolean;
  statusCode: number;
  message: string;
  error: {
    code: string;
    message: string;
  };
  timestamp: string;
  path: string;
}

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

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

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let errorCode = ERROR_CODES.INTERNAL_SERVER_ERROR;
    let message = 'An unexpected error occurred';

    if (exception instanceof Error) {
      this.logger.error(`Unhandled Exception: ${exception.message}`, exception.stack);

      if (exception.message.includes('ECONNREFUSED')) {
        status = HttpStatus.SERVICE_UNAVAILABLE;
        errorCode = ERROR_CODES.SERVICE_UNAVAILABLE;
        message = 'Database connection failed';
      } else if (exception.message.includes('timeout')) {
        status = HttpStatus.REQUEST_TIMEOUT;
        errorCode = ERROR_CODES.TIMEOUT;
        message = 'Operation timeout';
      }
    } else {
      this.logger.error('Unhandled Exception:', exception);
    }

    const errorResponse: ErrorResponse = {
      success: false,
      statusCode: status,
      message,
      error: {
        code: errorCode,
        message,
      },
      timestamp: new Date().toISOString(),
      path: request.url,
    };

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