using ErsatzTV.Middleware;
using Microsoft.AspNetCore.Http;
using NUnit.Framework;
using Shouldly;

namespace ErsatzTV.Tests.Middleware;

[TestFixture]
public class RequestLogScrubberTests
{
    private static HttpRequest RequestFor(string path, string queryString)
    {
        var context = new DefaultHttpContext();
        context.Request.Path = path;
        context.Request.QueryString = new QueryString(queryString);
        return context.Request;
    }

    [Test]
    public void Redacts_access_token_but_keeps_other_query_params()
    {
        HttpRequest request = RequestFor(
            "/iptv/channel/1.m3u8",
            "?mode=segmenter&access_token=eyJhbGciOiJIUzI1NiJ9.secret.sig");

        string scrubbed = RequestLogScrubber.ScrubbedPath(request);

        scrubbed.ShouldNotContain("secret");
        scrubbed.ShouldNotContain("eyJhbGciOiJIUzI1NiJ9");
        scrubbed.ShouldContain("access_token=***");
        scrubbed.ShouldContain("mode=segmenter");
        scrubbed.ShouldStartWith("/iptv/channel/1.m3u8?");
    }

    [Test]
    public void Redaction_is_case_insensitive_on_the_key()
    {
        HttpRequest request = RequestFor("/iptv/xmltv.xml", "?Access_Token=secret");

        RequestLogScrubber.ScrubbedPath(request).ShouldNotContain("secret");
    }

    [Test]
    public void Path_without_query_is_returned_verbatim()
    {
        HttpRequest request = RequestFor("/app", string.Empty);

        RequestLogScrubber.ScrubbedPath(request).ShouldBe("/app");
    }
}
