using System.Text.Json;

namespace economy.Models.Gold
{
    public class GoldModel
    {
        private readonly DataGoKR _dataGoKR;

        public GoldModel(DataGoKR dataGoKR)
        {
            _dataGoKR = dataGoKR;
        }

        // 금 시세 조회
        public async Task<Response> GetGoldPriceInfo(Request request)
        {
            Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/1160100/service/GetGeneralProductInfoService/getGoldPriceInfo",
                    Query = $"serviceKey={_dataGoKR.APIKey}&pageNo={request.PageNo}&numOfRows={request.NumOfRows}&beginBasDt={request.StartDate:yyyyMMdd}&endBasDt={request.EndDate:yyyyMMdd}&resultType=json"
                };

                if (request.LikeSrtnCd is not null)
                {
                    uriBuilder.Query += $"&likeSrtnCd={request.LikeSrtnCd}";
                }

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

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

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        var resEle = document.RootElement.GetProperty("response");

                        parseData = JsonSerializer.Deserialize<Response>(resEle.GetRawText());
                    }

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

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

            return parseData;
        }
    }
}
