using ClaudeDo.Worker.Config;
using Microsoft.AspNetCore.Http;

namespace ClaudeDo.Worker.External;

public sealed class ExternalMcpAuthMiddleware
{
    private const string HeaderName = "X-ClaudeDo-Key";

    private readonly RequestDelegate _next;

    public ExternalMcpAuthMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext ctx, WorkerConfig cfg)
    {
        if (string.IsNullOrEmpty(cfg.ExternalMcpApiKey))
        {
            await _next(ctx);
            return;
        }

        var provided = ctx.Request.Headers[HeaderName].ToString();
        if (!string.Equals(provided, cfg.ExternalMcpApiKey, StringComparison.Ordinal))
        {
            ctx.Response.StatusCode = 401;
            await ctx.Response.WriteAsync($"Missing or invalid {HeaderName} header");
            return;
        }

        await _next(ctx);
    }
}
