using System.Net;
using System.Net.Http;
using StellaOps.Feedser.Source.Common.Testing;

namespace StellaOps.Feedser.Source.Common.Tests;

public sealed class CannedHttpMessageHandlerTests
{
    [Fact]
    public async Task SendAsync_RecordsRequestsAndSupportsFallback()
    {
        var handler = new CannedHttpMessageHandler();
        var requestUri = new Uri("https://example.test/api/resource");
        handler.AddResponse(HttpMethod.Get, requestUri, () => new HttpResponseMessage(HttpStatusCode.OK));
        handler.SetFallback(_ => new HttpResponseMessage(HttpStatusCode.NotFound));

        using var client = handler.CreateClient();
        var firstResponse = await client.GetAsync(requestUri);
        var secondResponse = await client.GetAsync(new Uri("https://example.test/other"));

        Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, secondResponse.StatusCode);
        Assert.Equal(2, handler.Requests.Count);
        handler.AssertNoPendingResponses();
    }

    [Fact]
    public async Task AddException_ThrowsDuringSend()
    {
        var handler = new CannedHttpMessageHandler();
        var requestUri = new Uri("https://example.test/api/error");
        handler.AddException(HttpMethod.Get, requestUri, new InvalidOperationException("boom"));

        using var client = handler.CreateClient();
        await Assert.ThrowsAsync<InvalidOperationException>(() => client.GetAsync(requestUri));
    }
}
