using System.Collections.Generic;
using System.Globalization;
using StellaOps.Feedser.Source.Ghsa.Internal;
using Xunit;

namespace StellaOps.Feedser.Source.Ghsa.Tests.Ghsa;

public class GhsaRateLimitParserTests
{
    [Fact]
    public void TryParse_ReturnsSnapshot_WhenHeadersPresent()
    {
        var now = DateTimeOffset.UtcNow;
        var reset = now.AddMinutes(5);

        var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            ["X-RateLimit-Limit"] = "5000",
            ["X-RateLimit-Remaining"] = "42",
            ["X-RateLimit-Used"] = "4958",
            ["X-RateLimit-Reset"] = reset.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture),
            ["X-RateLimit-Resource"] = "core"
        };

        var snapshot = GhsaRateLimitParser.TryParse(headers, now, "list");

        Assert.True(snapshot.HasValue);
        Assert.Equal("list", snapshot.Value.Phase);
        Assert.Equal("core", snapshot.Value.Resource);
        Assert.Equal(5000, snapshot.Value.Limit);
        Assert.Equal(42, snapshot.Value.Remaining);
        Assert.Equal(4958, snapshot.Value.Used);
        Assert.NotNull(snapshot.Value.ResetAfter);
        Assert.True(snapshot.Value.ResetAfter!.Value.TotalMinutes <= 5.1 && snapshot.Value.ResetAfter.Value.TotalMinutes >= 4.9);
    }

    [Fact]
    public void TryParse_ReturnsNull_WhenHeadersMissing()
    {
        var snapshot = GhsaRateLimitParser.TryParse(null, DateTimeOffset.UtcNow, "list");
        Assert.Null(snapshot);
    }

    [Fact]
    public void TryParse_HandlesRetryAfter()
    {
        var now = DateTimeOffset.UtcNow;
        var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            ["Retry-After"] = "60"
        };

        var snapshot = GhsaRateLimitParser.TryParse(headers, now, "detail");

        Assert.True(snapshot.HasValue);
        Assert.Equal("detail", snapshot.Value.Phase);
        Assert.NotNull(snapshot.Value.RetryAfter);
        Assert.Equal(60, Math.Round(snapshot.Value.RetryAfter!.Value.TotalSeconds));
    }
}
