using System.Net;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
using Microsoft.eShopWeb.ApplicationCore.Services;
using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Xunit;

namespace Microsoft.eShopWeb.UnitTests.ApplicationCore.Services;

public class ExchangeRateClientTests
{
    [Fact]
    public async Task ParseLatest()
    {
        var exchangeRate = 1.5m;
        
        var obj = new ExchangeRateClient(new HttpClient(new TestHttpHandler(Currency.CAD, exchangeRate)));
        
        var result = await obj.Latest(Currency.USD, Currency.CAD);
        
        Assert.Equal(exchangeRate, result);
    }
    
    [Fact]
    public async Task MockHttpClient()
    {
        var exchangeRate = 1.5m;
        
        var mockHttp = new MockHttpMessageHandler();
        mockHttp.When("https://data.fixer.io/api/latest")
            .Respond("application/json", JsonConvert.SerializeObject(new { Rates = new Dictionary<string, decimal> { { Currency.CAD.ToString(), exchangeRate } } }));
        
        var obj = new ExchangeRateClient(mockHttp.ToHttpClient());
        
        var result = await obj.Latest(Currency.USD, Currency.CAD);
        
        Assert.Equal(exchangeRate, result);
    }
}

public class TestHttpHandler : HttpMessageHandler
{
    private readonly Currency _toCurrency;
    private readonly decimal _exchangeRate;

    public TestHttpHandler(Currency toCurrency, decimal exchangeRate)
    {
        _toCurrency = toCurrency;
        _exchangeRate = exchangeRate;
    }
    
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        var json = JsonConvert.SerializeObject(new { Rates = new Dictionary<string, decimal> { { _toCurrency.ToString(), _exchangeRate } } });
        response.Content = new StringContent(json);
        return Task.FromResult(response);
    }
}
