using economy.Helpers;

namespace economy.Models.Whois
{
    public class WhoisModel
    {
        private readonly DataGoKR _dataGoKR;

        public WhoisModel(DataGoKR dataGoKR)
        {
            _dataGoKR = dataGoKR;
        }

        // Domain 조회
        public async Task<Domain.Response> GetDomainInfo(string query)
        {
            Domain.Response parsedData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/B551505/whois/domain_name",
                    Query = $"serviceKey={_dataGoKR.APIKey}&query={query}&answer=xml"
                };

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

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

                    if (parsedData.Result.ResultCode is 10000)
                    {
                        return parsedData;
                    }
                }

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

            return parsedData;
        }

        // IP 조회
        public async Task<IP.Response> GetIPInfo(string query)
        {
            IP.Response parsedData = new();

            try
            {
                var uriBuilder = new UriBuilder(_dataGoKR.APIUrl)
                {
                    Path = "/B551505/whois/ip_address",
                    Query = $"serviceKey={_dataGoKR.APIKey}&query={query}&answer=xml"
                };

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

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

                    if (parsedData.Result.ResultCode is 10000)
                    {
                        return parsedData;
                    }
                }

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

            return parsedData;
        }
    }
}
