using economy.Helpers;

namespace economy.Models.Product
{
    public class ProductModel
    {
        private readonly DataGoKR _dataGoKR;

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

        // 품목별 가격 목록 조회
        public async Task<List.Response> GetPriceItemList(List.Request request)
        {
            List.Response parsedData = new();

            try
            {
                var response = await _dataGoKR.httpClient.GetAsync($"/1240000/bpp_openapi/getPriceItemList?ServiceKey={_dataGoKR.APIKey}&pageNo={request.PageNo}&numOfRows={request.NumOfRows}");

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

                    if (parsedData.Body is null)
                    {
                        return parsedData;
                    }
                }

                response.EnsureSuccessStatusCode(); // 예외 발생시킴

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

            return parsedData;
        }

        // 품목 상세 정보 조회
        public async Task<Detail.Response> GetPriceItemInfo(Detail.Request request)
        {
            Detail.Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/1240000/bpp_openapi/getPriceInfo",
                    Query = $"ServiceKey={_dataGoKR.APIKey}&pageNo={request.PageNo}&numOfRows={request.NumOfRows}&startDate={request.StartDate:yyyy-MM-dd}&endDate={request.EndDate:yyyy-MM-dd}&itemCode={request.ItemCode}"
                };

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

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


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

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

            return parseData;
        }
    }
}
