using System.Net;
using System.Net.Http;

namespace ClaudeDo.Releases.Tests;

internal sealed class FakeHttpMessageHandler : HttpMessageHandler
{
    private readonly Func<HttpRequestMessage, HttpResponseMessage> _handler;
    private readonly object _lock = new();
    private readonly List<HttpRequestMessage> _requests = new();

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

    public FakeHttpMessageHandler(HttpStatusCode status, string body)
        : this(_ => new HttpResponseMessage(status) { Content = new StringContent(body) })
    {
    }

    public IReadOnlyList<HttpRequestMessage> Requests
    {
        get { lock (_lock) return _requests.ToArray(); }
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        lock (_lock) _requests.Add(request);
        return Task.FromResult(_handler(request));
    }
}
