using adas_core.Application.Exceptions;
using adas_core.Domain.Exceptions;
using Microsoft.AspNetCore.Mvc;

namespace adas_core.ErrorMiddleware;
public class ErrorHandlerMiddleware(RequestDelegate next, ILogger<ErrorHandlerMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            var traceId = context.TraceIdentifier;

            logger.LogError(ex, "Unhandled exception. TraceId: {TraceId}", traceId);

            context.Response.ContentType = "application/json";

            var (statusCode, title) = ex switch
            {
                NotFoundException => (StatusCodes.Status404NotFound, "Resource not found"),
                CustomArgumentException => (StatusCodes.Status400BadRequest, "Invalid parameters"),
                InvalidFormatException => (StatusCodes.Status400BadRequest, "Invalid format"),
                BadRequestException => (StatusCodes.Status400BadRequest, "Bad request"),
                ConflictException => (StatusCodes.Status409Conflict, "Conflict"),
                ForbbidenException => (StatusCodes.Status403Forbidden, "Forbidden"),
                UnauthorizedAccessException => (StatusCodes.Status401Unauthorized, "Unauthorized"),
                LoginServicesNotFoundException => (StatusCodes.Status401Unauthorized, "Unauthorized"),
                UnauthorizedException => (StatusCodes.Status401Unauthorized, "Unauthorized"),
                UnprocessableEntityException => (StatusCodes.Status422UnprocessableEntity, "Unprocessable entity"),
                TokenException => (StatusCodes.Status401Unauthorized, "Invalid token"),
                _ => (StatusCodes.Status500InternalServerError, "Internal server error")
            };

            context.Response.StatusCode = statusCode;

            var problem = new ProblemDetails
            {
                Status = statusCode,
                Title = title,
                Detail = statusCode == 500
                    ? "An unexpected error occurred"
                    : null, // no exponer detalles
                Instance = context.Request.Path
            };

            // correlation id para soporte/debug
            problem.Extensions["traceId"] = traceId;

            await context.Response.WriteAsJsonAsync(problem);
        }
    }
}