using Microsoft.AspNetCore.Http;
using StellaOps.Configuration;

namespace StellaOps.Authority.Bootstrap;

internal sealed class BootstrapApiKeyFilter : IEndpointFilter
{
    private readonly StellaOpsAuthorityOptions options;

    public BootstrapApiKeyFilter(StellaOpsAuthorityOptions options)
    {
        this.options = options ?? throw new ArgumentNullException(nameof(options));
    }

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        if (!options.Bootstrap.Enabled)
        {
            return Results.NotFound();
        }

        if (!context.HttpContext.Request.Headers.TryGetValue("X-StellaOps-Bootstrap-Key", out var key) ||
            !string.Equals(key.ToString(), options.Bootstrap.ApiKey, StringComparison.Ordinal))
        {
            return Results.Unauthorized();
        }

        return await next(context).ConfigureAwait(false);
    }
}
