using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;

namespace Microsoft.eShopWeb.ApplicationCore.Services;

public class ExchangeRateClient : IExchangeRateClient
{
    private readonly HttpClient _httpClient;

    public ExchangeRateClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    
    public async Task<decimal> Latest(Currency baseCurrency, Currency toCurrency)
    {
        var result = await _httpClient.GetFromJsonAsync<JsonResponse>($"https://data.fixer.io/api/latest?base={baseCurrency}&symbols={toCurrency}");
        if (result == null)
        {
            throw new InvalidOperationException("Not a valid JSON response.");
        }
        
        return result.Rates.Single(x => x.Key == toCurrency.ToString()).Value;
    }

    private class JsonResponse
    {
        public Dictionary<string, decimal> Rates { get; set; }
    }
}
