using System.Text.Json;

namespace economy.Models.International
{
    public class InternationalModel
    {
        private readonly KoreaEximGoKR _koreaEximGoKR;

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

        // 국제 금리 조회
        public async Task<Response> GetInternationalRate(Request request)
        {
            Response parseData = new();

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

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

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

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

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

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

            return parseData;
        }
    }
}