using ApiOPE.Contracts;
using Microsoft.AspNetCore.Diagnostics;

namespace ApiOPE.Security;

public static class OpeExceptionHandler
{
    public static async Task HandleAsync(HttpContext context)
    {
        var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
        var requestContext = OpeRequestContextStore.Get(context);
        var logger = context.RequestServices
            .GetRequiredService<ILoggerFactory>()
            .CreateLogger("ApiOPE.UnhandledException");

        logger.LogError(
            exception,
            "Error no controlado en la operacion OPE. Path={Path}; TransactionId={TransactionId}",
            context.Request.Path,
            requestContext?.TransactionId);

        context.Response.Clear();
        await OpeResponseWriter.WriteErrorAsync(
            context.Response,
            StatusCodes.Status412PreconditionFailed,
            "Error en el conector",
            OpeErrorCauses.ConnectorError,
            null,
            context.RequestAborted);
    }
}
