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

/**
 * Global Exception Filter
 * مرشح استثناءات عالمي
 * 
 * Why: To maintain a consistent error response format across the entire SaaS platform.
 * لماذا: للحفاظ على تنسيق استجابة خطأ متسق عبر منصة البرمجيات كخدمة بالكامل.
 */
@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>();
    
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

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

    // Log the error for the developer | تسجيل الخطأ للمطور
    this.logger.error(
      `HTTP Status: ${status} Error: ${JSON.stringify(message)} Path: ${request.url}`,
    );

    // Return structured JSON | إرجاع استجابة منظمة
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: typeof message === 'object' ? (message as any).message : message,
    });
  }
}
