using System;
using System.Net;
using StellaOps.Auth.ServerIntegration;
using Xunit;

namespace StellaOps.Auth.ServerIntegration.Tests;

public class StellaOpsResourceServerOptionsTests
{
    [Fact]
    public void Validate_NormalisesCollections()
    {
        var options = new StellaOpsResourceServerOptions
        {
            Authority = "https://authority.stella-ops.test",
            BackchannelTimeout = TimeSpan.FromSeconds(10),
            TokenClockSkew = TimeSpan.FromSeconds(30)
        };

        options.Audiences.Add(" api://feedser ");
        options.Audiences.Add("api://feedser");
        options.Audiences.Add("api://feedser-admin");

        options.RequiredScopes.Add(" Feedser.Jobs.Trigger ");
        options.RequiredScopes.Add("feedser.jobs.trigger");
        options.RequiredScopes.Add("AUTHORITY.USERS.MANAGE");

        options.BypassNetworks.Add("127.0.0.1/32");
        options.BypassNetworks.Add(" 127.0.0.1/32 ");
        options.BypassNetworks.Add("::1/128");

        options.Validate();

        Assert.Equal(new Uri("https://authority.stella-ops.test"), options.AuthorityUri);
        Assert.Equal(new[] { "api://feedser", "api://feedser-admin" }, options.Audiences);
        Assert.Equal(new[] { "authority.users.manage", "feedser.jobs.trigger" }, options.NormalizedScopes);
        Assert.True(options.BypassMatcher.IsAllowed(IPAddress.Parse("127.0.0.1")));
        Assert.True(options.BypassMatcher.IsAllowed(IPAddress.IPv6Loopback));
    }

    [Fact]
    public void Validate_Throws_When_AuthorityMissing()
    {
        var options = new StellaOpsResourceServerOptions();

        var exception = Assert.Throws<InvalidOperationException>(() => options.Validate());

        Assert.Contains("Authority", exception.Message, StringComparison.OrdinalIgnoreCase);
    }
}
