
using System.Diagnostics.CodeAnalysis;
using System.Net;

namespace User.Insight.Tracker.Common
{
    [ExcludeFromCodeCoverage]
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlerMiddleware> _logger;

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

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Something went wrong. Exception Type: {ExceptionType}, Message: {Message}", ex.GetType().Name, ex.Message);
                await HandleExceptionAsync(context, ex);
            }

            if (context.Response.StatusCode == 401)
            {
                await Handle401ErrorAsync(context);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            return context.Response.WriteAsync(new
            {                
                Message = $"Exception code-{context.Response.StatusCode}-Message-{exception.Message}"
            }.ToString());
        }

        private static Task Handle401ErrorAsync(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            return context.Response.WriteAsync(new
            {
                StatusCode = context.Response.StatusCode,
                Message = "Not valid user"
            }.ToString());
        }
    }

}
