using Microsoft.Extensions.Options;

namespace MailPrint;

/// <summary>
/// Schützt alle /api/* Routen mit einem statischen API-Key.
/// Header: X-Api-Key: <key>
/// Wenn kein Key konfiguriert ist, wird die Middleware übersprungen.
/// </summary>
public class ApiKeyMiddleware
{
    private const string HeaderName = "X-Api-Key";
    private readonly RequestDelegate _next;
    private readonly string _apiKey;
    private readonly ILogger<ApiKeyMiddleware> _logger;

    public ApiKeyMiddleware(RequestDelegate next, IOptions<MailPrintOptions> options, ILogger<ApiKeyMiddleware> logger)
    {
        _next = next;
        _apiKey = options.Value.WebApi.ApiKey;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Kein API-Key konfiguriert → durchlassen (Entwicklung / lokales Netz)
        if (string.IsNullOrEmpty(_apiKey))
        {
            await _next(context);
            return;
        }

        // Swagger UI immer erlauben
        if (context.Request.Path.StartsWithSegments("/swagger"))
        {
            await _next(context);
            return;
        }

        if (!context.Request.Headers.TryGetValue(HeaderName, out var provided) ||
            provided != _apiKey)
        {
            _logger.LogWarning("Ungültiger API-Key von {IP}", context.Connection.RemoteIpAddress);
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsJsonAsync(new { error = "Ungültiger oder fehlender API-Key." });
            return;
        }

        await _next(context);
    }
}
