using System.Text;
using System.Text.Json;

namespace economy.Models.Lotto
{
    public class LottoModel
    {
        private readonly DhlotteryCoKR _dhlotteryCoKR;

        public LottoModel(DhlotteryCoKR dhlotteryCoKR)
        {
            _dhlotteryCoKR = dhlotteryCoKR;
        }

        // 로또 당첨 번호 조회
        public async Task<Response> GetLottoNumber(Request request)
        {
            Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dhlotteryCoKR.APIUrl)
                {
                    Path = "/common.do",
                    Query = $"method=getLottoNumber&drwNo={request.Number}"
                };

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

                if (response.IsSuccessStatusCode)
                {
                    var bytes = await response.Content.ReadAsByteArrayAsync();
                    var jsonString = Encoding.GetEncoding("euc-kr").GetString(bytes);
                    parseData = JsonSerializer.Deserialize<Response>(jsonString);
                    
                    if (parseData is null)
                    {
                        return new Response();
                    }
                }

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

            return parseData;
        }
    }
}
