using MEU.API.Utils;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace MEU.API.MiddleWare
{
    public class ErrorHandlingMiddleware
    {
        public static bool enableDebug = true;
        private readonly RequestDelegate next;
        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context /* other dependencies */)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if (ErrorHandlingMiddleware.enableDebug)
            {
                var code = System.Net.HttpStatusCode.InternalServerError; 
                var result = JsonConvert.SerializeObject(new { success = false, message = ex });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)code;
                return context.Response.WriteAsync(result);
            }
            else
            {
                var code = System.Net.HttpStatusCode.InternalServerError; // 500 if unexpected
                var result = JsonConvert.SerializeObject(new { success = false, message = "Unexpected error, please contact admin" });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)code;
                return context.Response.WriteAsync(result);
            }

        }
    }
}
