using Microsoft.AspNetCore.WebUtilities;
using Shouldly;

namespace JSMR.Tests.Http;

internal sealed class FakeHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler) : HttpMessageHandler
{
    public List<HttpRequestMessage> Requests { get; } = [];

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Requests.Add(request);

        return Task.FromResult(handler(request));
    }
}

public static class HttpRequestMessageAssertions
{
    public static void ShouldHavePath(this HttpRequestMessage request, string expectedPath)
    {
        request.RequestUri.ShouldNotBeNull();
        request.RequestUri!.AbsolutePath.ShouldBe(expectedPath);
    }

    public static void ShouldHaveQueryParam(this HttpRequestMessage request, string key, string expectedValue)
    {
        request.RequestUri.ShouldNotBeNull();

        var query = QueryHelpers.ParseQuery(request.RequestUri!.Query);
        query[key].ToString().ShouldBe(expectedValue);
    }
}

//internal sealed class FakeHttpMessageHandler : HttpMessageHandler
//{
//    private readonly Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> _handler;

//    public List<HttpRequestMessage> Requests { get; } = [];

//    public FakeHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> handler)
//    {
//        _handler = handler;
//    }

//    public FakeHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
//        : this((request, _) => handler(request))
//    {
//    }

//    protected override Task<HttpResponseMessage> SendAsync(
//        HttpRequestMessage request,
//        CancellationToken cancellationToken)
//    {
//        Requests.Add(request);

//        HttpResponseMessage response = _handler(request, cancellationToken);
//        return Task.FromResult(response);
//    }
//}