using LSFE.Application.Common.Exceptions;
using LSFE.Application.Common.Models;
using System.Security.Claims;
using System.Text.Json;

namespace LSFE.API.Middleware
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalExceptionMiddleware> _logger;
        private readonly IHostEnvironment _env;

        public GlobalExceptionMiddleware(
            RequestDelegate next,
            ILogger<GlobalExceptionMiddleware> logger,
            IHostEnvironment env)
        {
            _next = next;
            _logger = logger;
            _env = env;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unhandled exception: {Message}", ex.Message);
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var (statusCode, message, errors) = ex switch
            {
                ValidationException e => (StatusCodes.Status422UnprocessableEntity,
                                            e.Message, e.Errors),

                NotFoundException e => (StatusCodes.Status404NotFound,
                                            e.Message, null),

                UnauthorizedException e => (StatusCodes.Status401Unauthorized,
                                            e.Message, null),

                ForbiddenException e => (StatusCodes.Status403Forbidden,
                                            e.Message, null),

                BusinessRuleException e => (StatusCodes.Status409Conflict,
                                            e.Message, null),

                UnauthorizedAccessException e => (StatusCodes.Status401Unauthorized,
                                                  e.Message, null),

                OperationCanceledException _ => (StatusCodes.Status499ClientClosedRequest,
                                                  "Request was cancelled.", null),

                _ => (StatusCodes.Status500InternalServerError,
                      "An unexpected error occurred. Please try again later.", null)
            };

            var response = new ErrorResponse
            {
                StatusCode = statusCode,
                Message = message,
                Errors = errors,
                StackTrace = _env.IsDevelopment() ? ex.StackTrace : null
            };

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

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