using System;
using StellaOps.Auth.Client;
using Xunit;

namespace StellaOps.Auth.Client.Tests;

public class StellaOpsAuthClientOptionsTests
{
    [Fact]
    public void Validate_NormalizesScopes()
    {
        var options = new StellaOpsAuthClientOptions
        {
            Authority = "https://authority.test",
            ClientId = "cli",
            HttpTimeout = TimeSpan.FromSeconds(15)
        };
        options.DefaultScopes.Add(" Feedser.Jobs.Trigger ");
        options.DefaultScopes.Add("feedser.jobs.trigger");
        options.DefaultScopes.Add("AUTHORITY.USERS.MANAGE");

        options.Validate();

        Assert.Equal(new[] { "authority.users.manage", "feedser.jobs.trigger" }, options.NormalizedScopes);
        Assert.Equal(new Uri("https://authority.test"), options.AuthorityUri);
        Assert.Equal<TimeSpan>(options.RetryDelays, options.NormalizedRetryDelays);
    }

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

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

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

    [Fact]
    public void Validate_NormalizesRetryDelays()
    {
        var options = new StellaOpsAuthClientOptions
        {
            Authority = "https://authority.test"
        };
        options.RetryDelays.Clear();
        options.RetryDelays.Add(TimeSpan.Zero);
        options.RetryDelays.Add(TimeSpan.FromSeconds(3));
        options.RetryDelays.Add(TimeSpan.FromMilliseconds(-1));

        options.Validate();

        Assert.Equal<TimeSpan>(new[] { TimeSpan.FromSeconds(3) }, options.NormalizedRetryDelays);
        Assert.Equal<TimeSpan>(options.NormalizedRetryDelays, options.RetryDelays);
    }

    [Fact]
    public void Validate_DisabledRetries_ProducesEmptyDelays()
    {
        var options = new StellaOpsAuthClientOptions
        {
            Authority = "https://authority.test",
            EnableRetries = false
        };

        options.Validate();

        Assert.Empty(options.NormalizedRetryDelays);
    }

    [Fact]
    public void Validate_Throws_When_OfflineToleranceNegative()
    {
        var options = new StellaOpsAuthClientOptions
        {
            Authority = "https://authority.test",
            OfflineCacheTolerance = TimeSpan.FromSeconds(-1)
        };

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

        Assert.Contains("Offline cache tolerance", exception.Message, StringComparison.OrdinalIgnoreCase);
    }
}
