using economy.Helpers;

namespace economy.Models.Sundry
{
    public class SundryModel
    {
        private readonly DataGoKR _dataGoKR;

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

        // 잡절 조회
        public async Task<Response> GetSundry(Request request)
        {
            Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/B090041/openapi/service/SpcdeInfoService/getSundryDayInfo",
                    Query = $"ServiceKey={_dataGoKR.APIKey}&numOfRows=100&solYear={request.Year}"
                };

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

                if (response.IsSuccessStatusCode)
                {
                    var xmlString = await response.Content.ReadAsStringAsync();
                    parseData = await Common.ParseXmlDataAsync<Response>(xmlString);


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

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

            return parseData;
        }
    }
}
