// import { Exception } from '@adonisjs/core/exceptions'
import { HttpContext, ExceptionHandler } from '@adonisjs/core/http';

export default class DbHandlerException extends ExceptionHandler {
    // constructor() {
    //   super(Logger)
    // }

    async handle(error: any, ctx: HttpContext) {
        // Check for AggregateError type
        if (error.type === 'AggregateError' && error.aggregateErrors) {
            const dbErrors = error.aggregateErrors.some((err: any) => err.code === 'ECONNREFUSED' && err.port === 5432);

            if (dbErrors) {
                return ctx.response.status(503).json({
                    status: 'error',
                    message: 'PostgreSQL database connection failed. Please ensure the database service is running.',
                    details: {
                        code: error.code,
                        type: error.type,
                        ports: error.aggregateErrors.map((err: any) => ({
                            port: err.port,
                            address: err.address,
                        })),
                    },
                });
            }
        }

        // Handle simple ECONNREFUSED errors
        if (error.code === 'ECONNREFUSED') {
            return ctx.response.status(503).json({
                status: 'error',
                message: 'Database connection failed. Please ensure PostgreSQL is running.',
                code: error.code,
            });
        }

        return super.handle(error, ctx);
    }

    static status = 500;
}
