using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using economy.Helpers;
using economy.Models;
using economy.Models.Whois;

namespace economy.Controllers
{
    public class WhoisController : Controller
    {
        [ViewData]
        [BindProperty(Name = "query", SupportsGet = true)]
        [Required(ErrorMessage = "검색어를 입력해주세요.")]
        [StringLength(120, ErrorMessage = "검색어 길이를 초과하였습니다.")]
        public required string Query { get; set; }

        private readonly DataGoKR _dataGoKR;
        private Dictionary<string, string> _queryString;

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

        [HttpGet]
        public IActionResult Index()
        {
            ViewBag.isError = false;

            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Search()
        {
            try
            {
                // 유효성 검사
                if (!ModelState.IsValid)
                {
                    throw new Exception(
                        string.Join("\n", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))
                    );
                }

                if (string.IsNullOrWhiteSpace(Query))
                {
                    throw new Exception("검색어를 입력해주세요.");                  
                }

                if (Common.IsDomain(Query))
                {
                    ViewBag.result = await _Domain();
                    ViewBag.type = 1;
                }
                else if (Common.IsIPv4(Query) || Common.IsIPv6(Query))
                {
                    ViewBag.result = await _IP();
                    ViewBag.type = 2;
                }
                else
                {
                    throw new Exception("형식이 옳지 않습니다. 올바른 도메인 또는 IP 주소를 입력해주세요.");
                }

                ViewBag.isError = false;
            }
            catch (Exception ex)
            {
                ViewBag.isError = true;
                ViewBag.errorMessage = ex.Message;
            }

            ViewBag.Query = Query;

            return View("Index");
        }

        // 도메인 검색
        private async Task<Models.Whois.Domain.Response> _Domain()
        {
            WhoisModel whois = new WhoisModel(_dataGoKR);
            Models.Whois.Domain.Response domainInfo = await whois.GetDomainInfo(Query);

            return domainInfo;
        }

        // IP 검색
        private async Task<Models.Whois.IP.Response> _IP()
        {
            WhoisModel whois = new WhoisModel(_dataGoKR);
            Models.Whois.IP.Response IPInfo = await whois.GetIPInfo(Query);

            return IPInfo;
        }
    }
}
