import { Request, Response, NextFunction } from 'express';
import logger from '../libs/logger';
import {CustomError} from '../types/custom'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const errorHandlerMiddleware = (
    error: CustomError,
    req: Request, 
    res: Response,
    next: NextFunction
) => {
    //checking error status in express error or if axios errors checks status in error.response.status
    let statusCode = (error.status || error.response?.status) || 500;
    if (error.message && error.message.includes('template')) {
        statusCode = 404;
    }
    const message = statusCode === 500 ? 'Internal Server Error' : error.message || 'Bad Request';
    logger.error(`Error occurred with status ${statusCode} and message: ${message} ${next}`);
    const errorPage = statusCode === 404 ? '/error404' : '/error500';
    return res.redirect(errorPage)
};

