namespace eSuite.API.Middleware;

/// <summary>
/// Adds support for the cors options pre-flight check
/// </summary>
public class OptionsMiddleware
{
    private readonly RequestDelegate _next;

    /// <summary>
    /// Default constructor
    /// </summary>
    /// <param name="next"></param>
    public OptionsMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    /// <summary>
    /// Called by asp.net.
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task Invoke(HttpContext context)
    {
        if (context.Request.Method == "OPTIONS")
        {
            context.Response.Headers.AccessControlAllowOrigin = (string)context.Request.Headers.Origin!;
            //context.Response.Headers.Add("Access-Control-Allow-Origin",
            //    new[] { (string)context.Request.Headers["Origin"] });
            //context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            context.Response.Headers.AccessControlAllowHeaders = new[] {"Origin, X-Requested-With, Content-Type, Accept, Authorization"};
            context.Response.Headers.AccessControlAllowMethods = new[] {"GET, POST, PUT, DELETE, OPTIONS"};
            context.Response.Headers.AccessControlAllowCredentials = new[] {"true"};
            context.Response.StatusCode = 200;
            return context.Response.WriteAsync("OK");
        }

        return _next.Invoke(context);
    }
}