using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;

namespace OnlineSalesAutoCrop.CoreAPI.Models.Global
{
	public class ErrorHandlingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
	{
		private readonly RequestDelegate _next = next;
		private readonly ILogger _logger = loggerFactory.CreateLogger<ErrorHandlingMiddleware>();

		public async Task Invoke(HttpContext context)
		{
			try
			{
				await _next(context);
			}
			catch (Exception ex)
			{
				await HandleExceptionAsync(context, ex);
			}
		}

		private Task HandleExceptionAsync(HttpContext context, Exception exception)
		{
			var code = HttpStatusCode.InternalServerError; // 500 if unexpected

			if (exception is ArgumentNullException)
				code = HttpStatusCode.BadRequest;
			else if (exception is ArgumentException)
				code = HttpStatusCode.BadRequest;
			else if (exception is UnauthorizedAccessException)
				code = HttpStatusCode.Unauthorized;

			_logger.LogError($"GLOBAL ERROR HANDLER::HTTP:{code}::{exception.Message}");

			var result = JsonConvert.SerializeObject(exception, Formatting.Indented);

			context.Response.Clear();
			context.Response.ContentType = "application/json";
			context.Response.StatusCode = (int)code;
			return context.Response.WriteAsync(result);
		}
	}
}
