using EVCB_OCPP.WEBAPI.Models.WebAPI;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;

namespace EVCB_OCPP.WEBAPI.Middleware;

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            var result = new CPOOuterResponse() {
                StatusMessage = CPO_StatusMessage.ERROR_MSG_Global_UNEXPECTEDERROR, 
                StatusCode = (int)CPO_StatusCode.UnexpectedError };

            var resultString = JsonConvert.SerializeObject(result, EVCBConfiguration.JSONSERIALIZER_FORMAT);

            await context.Response.WriteAsync(resultString);
        }
    }
}