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

namespace adas_core.ErrorMiddleware;

/// <summary>
/// Represents an ASP.NET Core middleware that handles errors occurring during the request processing pipeline.
/// </summary>
/// <remarks>
/// This middleware is typically registered in the application's request pipeline to intercept and handle exceptions
/// thrown by subsequent middleware components, while leveraging the injected logger to record error information.
/// </remarks>
public class ErrorHandlerMiddleware(RequestDelegate next, ILogger<ErrorHandlerMiddleware> logger)
{
    /// <summary>
    /// Middleware that catches unhandled exceptions, maps known domain exceptions to appropriate HTTP status codes, and writes a standardized <see cref="ProblemDetails"/> response with a correlation <c>traceId</c>. 
    /// For unrecognized exceptions, it falls back to a 500 Internal Server Error response without exposing internal details.
    /// </summary>
    /// <param name="context">The current HTTP request context used to invoke the next middleware, read the trace identifier, and write the error response.</param>
    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);
        }
    }
}