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

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const http_context = host.switchToHttp();
        const response     = http_context.getResponse<Response>();
        const request      = http_context.getRequest<Request>();
        const http_status  = exception.getStatus();

        const exception_response = exception.getResponse();
        const normalized = typeof exception_response === 'string'
                                                    ? { message: exception_response }
                                                    : (exception_response as Record<string, unknown>);
        const response_body = {
            statusCode: http_status,
            timestamp: new Date().toISOString(),
            path: request.url,
            ...normalized,
        };
        response.status(http_status).json(response_body);
    }
}