using System.Text.Json;

namespace economy.Models.Exchange
{
    public class ExchangeModel
    {
        private readonly KoreaEximGoKR _koreaEximGoKR;

        public ExchangeModel(KoreaEximGoKR koreaEximGoKR)
        {
            _koreaEximGoKR = koreaEximGoKR;
        }

        // 환율 조회
        public async Task<Response> GetExchange(Request request)
        {
            Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_koreaEximGoKR.APIUrl)
                {
                    Path = "/site/program/financial/exchangeJSON",
                    Query = $"authkey={_koreaEximGoKR.ExchangeAPIKey}&searchdate={request.Date:yyyyMMdd}&data=AP01"
                };

                var response = await _koreaEximGoKR.httpClient.GetAsync(uriBuilder.Uri);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        parseData.Items = JsonSerializer.Deserialize<List<Data>>(jsonString);
                    }

                    if (parseData is null)
                    {
                        return new Response();
                    }
                }

                response.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }

            return parseData;
        }
    }
}