using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StellaOps.Auth.Abstractions;
using StellaOps.Auth.ServerIntegration;
using Xunit;

namespace StellaOps.Auth.ServerIntegration.Tests;

public class ServiceCollectionExtensionsTests
{
    [Fact]
    public void AddStellaOpsResourceServerAuthentication_ConfiguresJwtBearer()
    {
        var configuration = new ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["Authority:ResourceServer:Authority"] = "https://authority.example",
                ["Authority:ResourceServer:Audiences:0"] = "api://feedser",
                ["Authority:ResourceServer:RequiredScopes:0"] = "feedser.jobs.trigger",
                ["Authority:ResourceServer:BypassNetworks:0"] = "127.0.0.1/32"
            })
            .Build();

        var services = new ServiceCollection();
        services.AddLogging();
        services.AddStellaOpsResourceServerAuthentication(configuration);

        using var provider = services.BuildServiceProvider();

        var resourceOptions = provider.GetRequiredService<IOptionsMonitor<StellaOpsResourceServerOptions>>().CurrentValue;
        var jwtOptions = provider.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>().Get(StellaOpsAuthenticationDefaults.AuthenticationScheme);

        Assert.NotNull(jwtOptions.Authority);
        Assert.Equal(new Uri("https://authority.example/"), new Uri(jwtOptions.Authority!));
        Assert.True(jwtOptions.TokenValidationParameters.ValidateAudience);
        Assert.Contains("api://feedser", jwtOptions.TokenValidationParameters.ValidAudiences);
        Assert.Equal(TimeSpan.FromSeconds(60), jwtOptions.TokenValidationParameters.ClockSkew);
        Assert.Equal(new[] { "feedser.jobs.trigger" }, resourceOptions.NormalizedScopes);
    }
}
