using Hl7.Fhir.Serialization;
using Microsoft.Extensions.Options;
using Task = System.Threading.Tasks.Task;

public class FhirApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly FhirOptions _options;
    private static readonly FhirJsonSerializer Serializer = new();

    public FhirApiKeyMiddleware(RequestDelegate next, IOptions<FhirOptions> options)
    {
        _next = next;
        _options = options.Value;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Path.StartsWithSegments("/fhir"))
        {
            await _next(context);
            return;
        }

        if (string.IsNullOrWhiteSpace(_options.ApiKey))
        {
            await _next(context);
            return;
        }

        if (!context.Request.Headers.TryGetValue("X-Api-Key", out var key) ||
            key != _options.ApiKey)
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            context.Response.ContentType = "application/fhir+json";
            var outcome = FhirOperationOutcomeBuilder.Create(401, "login", "Invalid or missing API key.");
            await context.Response.WriteAsync(Serializer.SerializeToString(outcome));
            return;
        }

        await _next(context);
    }
}