using System.Text.Json;

namespace economy.Models.Flower
{
    public class FlowerModel
    {
        private readonly FlowerAtOrKR _flowerAtOrKR;

        public FlowerModel(FlowerAtOrKR flowerAtOrKR)
        {
            _flowerAtOrKR = flowerAtOrKR;
        }

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

            try
            {
                var uriBuilder = new UriBuilder(_flowerAtOrKR.APIUrl)
                {
                    Path = "/api/returnData.api",
                    Query = $"kind=f001&serviceKey={_flowerAtOrKR.APIKey}&currentPage={request.PageNo}&countPerPage={request.NumOfRows}&baseDate={request.BaseDate:yyyy-MM-dd}&flowerGubn={(int)request.Type}&dataType=json"
                };

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

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

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

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

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        if (document.RootElement.TryGetProperty("response", out var resEle))
                        {
                            Console.WriteLine("Found 'response' property.");
                            Console.WriteLine(resEle.GetRawText()); // response 내부 텍스트 출력
                            parseData = JsonSerializer.Deserialize<Response>(resEle.GetRawText());
                        }
                        else
                        {
                            Console.WriteLine("'response' property not found in JSON.");
                        }
                    }

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

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

            return parseData;
        }
    }
}
