using System.Text.Json;

namespace economy.Models.Interest
{
    public class InterestModel
    {
        private readonly KoreaEximGoKR _koreaEximGoKR;

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

        // 대출 금리 조회
        public async Task<Response> GetInterestRate(Request request)
        {
            Response parseData = new();

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

                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.Items is null)
                    {
                        return new Response();
                    }
                }

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

            return parseData;
        }
    }
}