using Microsoft.AspNetCore.HttpOverrides;
using ZB.MOM.WW.ScadaBridge.Security;
using Xunit;

namespace ZB.MOM.WW.ScadaBridge.Security.Tests;

public class ForwardedHeadersSetupTests
{
    [Fact]
    public void Build_Disabled_ReturnsNull()
        => Assert.Null(ForwardedHeadersSetup.Build(new ForwardedHeadersSecurityOptions { Enabled = false }));

    [Fact]
    public void Build_Enabled_ParsesProxiesAndNetworks_AndClearsDefaults()
    {
        var built = ForwardedHeadersSetup.Build(new ForwardedHeadersSecurityOptions
        {
            Enabled = true,
            KnownProxies = ["10.5.0.9"],
            KnownNetworks = ["172.16.0.0/12"],
        })!;
        Assert.Equal(ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, built.ForwardedHeaders);
        Assert.Equal(1, built.ForwardLimit);
        Assert.Single(built.KnownProxies);                       // ONLY the configured proxy —
        Assert.DoesNotContain(System.Net.IPAddress.IPv6Loopback, // the loopback default is cleared
            built.KnownProxies);
        Assert.Single(built.KnownIPNetworks); // net10 successor to the deprecated KnownNetworks
    }

    [Theory]
    [InlineData("not-an-ip", "172.16.0.0/12")]
    [InlineData("10.5.0.9", "not-a-cidr")]
    public void Build_MalformedEntry_ThrowsAtStartup(string proxy, string network)
        => Assert.ThrowsAny<Exception>(() => ForwardedHeadersSetup.Build(
            new ForwardedHeadersSecurityOptions { Enabled = true, KnownProxies = [proxy], KnownNetworks = [network] }));
}
