using System.Net.Http.Headers;

namespace StellaOps.Feedser.Source.Common.Http;

/// <summary>
/// Delegating handler that enforces an allowlist of destination hosts for outbound requests.
/// </summary>
internal sealed class AllowlistedHttpMessageHandler : DelegatingHandler
{
    private readonly IReadOnlyCollection<string> _allowedHosts;

    public AllowlistedHttpMessageHandler(SourceHttpClientOptions options)
    {
        ArgumentNullException.ThrowIfNull(options);
        var snapshot = options.GetAllowedHostsSnapshot();
        if (snapshot.Count == 0)
        {
            throw new InvalidOperationException("Source HTTP client must configure at least one allowed host.");
        }

        _allowedHosts = snapshot;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(request);

        var host = request.RequestUri?.Host;
        if (string.IsNullOrWhiteSpace(host) || !_allowedHosts.Contains(host))
        {
            throw new InvalidOperationException($"Request host '{host ?? "<null>"}' is not allowlisted for this source.");
        }

        return base.SendAsync(request, cancellationToken);
    }
}
