import {
    ArgumentsHost,
    Catch,
    ExceptionFilter,
    HttpException,
    HttpStatus,
} from '@nestjs/common';
import { Counter } from 'prom-client';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Request, Response } from 'express';

@Catch()
export class MetricsExceptionFilter implements ExceptionFilter {
    constructor(
        @InjectMetric('app_exceptions_total')
        private readonly exceptionCounter: Counter<string>,
    ) { }

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

        const job = process.env.SERVICE_NAME || 'HUB-backend';
        const type = exception?.name || 'UnknownException';

        // 📊 Record metric (side-effect only)
        try {
            this.exceptionCounter.inc({ job, type }, 1);
        } catch (err) {
            // metrics must NEVER crash the app
            console.error('Metrics increment failed:', err);
        }

        // 🛑 Convert exception → HTTP response
        const status =
            exception instanceof HttpException
                ? exception.getStatus()
                : HttpStatus.INTERNAL_SERVER_ERROR;

        const body =
            exception instanceof HttpException
                ? exception.getResponse()
                : {
                    statusCode: status,
                    message: 'Internal server error',
                };

        // ✅ END the request lifecycle
        response.status(status).json(
            typeof body === 'string'
                ? { statusCode: status, message: body }
                : body,
        );
    }
}
