using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;

namespace economy.Models.Financial
{
    public class FinancialModel
    {
        private readonly KoreaEximGoKR _koreaEximGoKR;
        private readonly IMemoryCache _cache;

        public FinancialModel(KoreaEximGoKR koreaEximGoKR)
        {
            _koreaEximGoKR = koreaEximGoKR;
            _cache = new MemoryCache(new MemoryCacheOptions());
        }

        // 환율 조회
        public async Task<Exchange.Response> GetExchange(Exchange.Request request)
        {
            Exchange.Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_koreaEximGoKR.APIUrl)
                {
                    Path = "/site/program/financial/exchangeJSON",
                    Query = $"authkey={_koreaEximGoKR.ExchangeAPIKey}&searchdate={request.Date:yyyyMMdd}&data=AP01"
                };

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

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

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        parseData.Items = JsonSerializer.Deserialize<List<Exchange.Data>>(jsonString);
                    }

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

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

            return parseData;
        }

        // 대출 금리 조회
        public async Task<Interest.Response> GetInterestRate(Interest.Request request)
        {
            Interest.Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_koreaEximGoKR.APIUrl)
                {
                    Path = "/site/program/financial/interestJSON",
                    Query = $"authkey={_koreaEximGoKR.InterestAPIKey}&searchdate={request.Date:yyyyMMdd}&data=AP02"
                };

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

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

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        parseData.Items = JsonSerializer.Deserialize<List<Interest.Data>>(jsonString);
                    }

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

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

            return parseData;
        }

        // 국제 금리 조회
        public async Task<International.Response> GetInternationalRate(International.Request request)
        {
            International.Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_koreaEximGoKR.APIUrl)
                {
                    Path = "/site/program/financial/internationalJSON",
                    Query = $"authkey={_koreaEximGoKR.InternationalAPIKey}&searchdate={request.Date:yyyyMMdd}&data=AP03"
                };

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

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

                    using (var document = JsonDocument.Parse(jsonString))
                    {
                        parseData = JsonSerializer.Deserialize<International.Response>(jsonString);
                    }

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

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

            return parseData;
        }

        // 환율 원화 기준환율만 DB에 등록
        public async Task<int> GetExchangeValue()
        {
            string cacheKey = "ExchangeValue";

            // 캐시에 데이터가 존재하면 반환
            if (_cache.TryGetValue(cacheKey, out int cachedData))
            {
                return cachedData;
            }

            var request = new Exchange.Request
            {
                Date = DateOnly.FromDateTime(DateTime.Now).AddDays(-1)
            };

            Exchange.Response exchangeList = await GetExchange(request);

            int result = 0;

            if (exchangeList.Items != null)
            {
                var usdItem = exchangeList.Items.Where(item => item.CurUnit == "USD").Take(1).ToList();
               
                if (usdItem.Any())
                {
                    // 쉼표 제거 후 소수점 처리
                    var value = usdItem[0].DealBasRate.Replace(",", "");

                    if (decimal.TryParse(value, out var parsedRate))
                    {
                        result = (int)Math.Round(parsedRate);
                    }

                    // 캐시에 저장 (1일 동안 유지)
                    _cache.Set(cacheKey, result, TimeSpan.FromDays(1));
                }
            }

            return result;
        }
    }
}