using Microsoft.EntityFrameworkCore;
using System.Net;
using System.Text.Json;

namespace SwaggerAntifraude.Middlewares
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrió un error: {ex}"); 

                switch (ex)
                {
                    case DbUpdateException dbEx:
                        await HandleExceptionAsync(context, "Error al actualizar la base de datos.", HttpStatusCode.BadRequest);
                        break;
                    case KeyNotFoundException _:
                        await HandleExceptionAsync(context, "Recurso no encontrado.", HttpStatusCode.NotFound);
                        break;
                    default:
                        await HandleExceptionAsync(context, "Ocurrió un error inesperado. Por favor, inténtalo de nuevo más tarde.", HttpStatusCode.InternalServerError);
                        break;
                }
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, string message, HttpStatusCode statusCode)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)statusCode;

            var response = new { message };
            var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };

            return context.Response.WriteAsync(JsonSerializer.Serialize(response, options));
        }
    }
}
