/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const errorMessages: Record<number, string> = {
      400: 'Datos inválidos enviados por el cliente',
      401: 'Falta autenticación',
      403: 'No tienes permisos para acceder',
      404: 'El recurso no existe',
      500: 'Error interno del servidor',
    };

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : 'Error inesperado';

    response.status(status).json({
      statusCode: status,
      message: errorMessages[status] || message,
      timestamp: new Date().toISOString(),
      path: ctx.getRequest().url,
    });
  }
}
