using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using economy.Models;
using economy.Models.Business.Number;

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

        private readonly NTS_API _NTS_API;
        private Dictionary<string, string> _queryString;

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

        [HttpGet]
        public IActionResult Number()
        {
            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("검색어를 입력해주세요.");                  
                }

                BusinessModel business = new BusinessModel(_NTS_API);

                ViewBag.result = await business.GetNumberInfo(Query);
                ViewBag.isError = false;
            }
            catch (Exception ex)
            {
                ViewBag.isError = true;
                ViewBag.errorMessage = ex.Message;
            }

            ViewBag.Query = Query;

            return View("Number");
        }
    }
}
