using System.Text.Json;
using economy.Helpers;

namespace economy.Models.Price.Domestic
{
    public class DomesticModel
    {
        private readonly DataGoKR? _dataGoKR;
        private readonly FlowerAtOrKR? _flowerAtOrKR;

        public DomesticModel(DataGoKR? dataGoKR, FlowerAtOrKR? flowerAtOrKR)
        {
            _dataGoKR = dataGoKR;
            _flowerAtOrKR = flowerAtOrKR;
        }

        // 금 시세 조회
        public async Task<Gold.Response> GetGoldPriceInfo(Gold.Request request)
        {
            Gold.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<Gold.Response>(resEle.GetRawText());
                    }

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

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

            return parseData;
        }

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

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

                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<Oil.Response>(resEle.GetRawText());
                    }

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

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

            return parseData;
        }

        // 배출권 시세 조회
        public async Task<Emission.Response> GetEmissionPriceInfo(Emission.Request request)
        {
            Emission.Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/1160100/service/GetGeneralProductInfoService/getCertifiedEmissionReductionPriceInfo",
                    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<Emission.Response>(resEle.GetRawText());
                    }

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

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

            return parseData;
        }

        // 품목별 가격 목록 조회
        public async Task<Item.List.Response> GetPriceItemList(Item.List.Request request)
        {
            Item.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<Item.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<Item.Detail.Response> GetPriceItemInfo(Item.Detail.Request request)
        {
            Item.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<Item.Detail.Response>(xmlString);


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

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

            return parseData;
        }

        // 화훼 시세 조회
        public async Task<Flower.Response> GetFlowerPriceInfo(Flower.Request request)
        {
            Flower.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<Flower.Response>(resEle.GetRawText());
                        }
                        else
                        {
                            Console.WriteLine("'response' property not found in JSON.");
                        }
                    }

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

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

            return parseData;
        }
    }
}
