using economy.Helpers;
using System.Text;
using System.Text.Json;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace economy.Models.Business.Number
{
    /**
     * http://api.odcloud.kr/api/nts-businessman/v1/status?serviceKey=vQz8tIxrdhjerG6DE1w1hcVEli5S27LtIsCvx0axiieZmRgOpB4vToQ77VmvknAkIC9YjxlPx2gDZcl06S88Xw%3D%3D&returnType=XML
     */
    public class BusinessModel
    {
        private readonly NTS_API _NTS_API;

        public BusinessModel(NTS_API NTS_API)
        {
            _NTS_API = NTS_API;
        }

        // 사업자 상태 조회
        public async Task<Number.Response> GetNumberInfo(string query)
        {
            Number.Response parsedData = new();

            try
            {
                var uriBuilder = new UriBuilder(_NTS_API.APIUrl)
                {
                    Path = "/api/nts-businessman/v1/status",
                    Query = $"serviceKey={_NTS_API.APIKey}&returnType=XML"
                };

                query = query.Trim().Replace("-", "");

                var jsonData = JsonSerializer.Serialize(new
                {
                    b_no = new[] { query }
                });
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await _NTS_API.httpClient.PostAsync(uriBuilder.Uri, content);

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

                    if (parsedData.StatusCode == "OK")
                    {
                        return parsedData;
                    }
                }

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

            return parsedData;
        }
    }
}
