using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using goods.Models;
using goods.Models.Coupang;
using Product = goods.Models.Coupang.Product;
using Search = goods.Models.Coupang.Search;

namespace goods.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly CoupangPartners _coupangPartners;
        private readonly DBContext _context;

        public HomeController(ILogger<HomeController> logger, CoupangPartners coupangPartners, DBContext context)
        {
            _logger = logger;
            _coupangPartners = coupangPartners;
            _context = context;
        }

        // 홈(메인)
        [HttpGet("/")]
        public IActionResult Index()
        {
            return View();
        }

        // 이벤트
        [HttpGet("/Event")]
        public IActionResult Event()
        {
            var data = new(int key, string href, string src, string alt)[]
            {
                (1, "https://link.coupang.com/a/b69T8Q", "/image/1.png", "패션 LAST SALE! 최대 70% 할인"),
                (2, "https://link.coupang.com/a/b69UJh", "/image/2.png", "기분 좋은 선물! E쿠폰/기프티콘"),
                (3, "https://link.coupang.com/a/b69UPW", "/image/3.png", "골드박스"),
                (4, "https://link.coupang.com/a/b69UUT", "/image/4.png", "펜션/풀빌라 와우회원 할인"),
                (5, "https://link.coupang.com/a/b69UYJ", "/image/5.png", "로켓프레시, 맛있는 최저가"),

                (6, "https://link.coupang.com/a/b69U57", "/image/6.png", "[모바일 전용] 쿠팡라이브 럭키박스"),
                (7, "https://link.coupang.com/a/b69VaS", "/image/7.png", "로켓패션, 역대급 할인 아울렛관"),
                (8, "https://link.coupang.com/a/b69VfM", "/image/8.png", "로켓프레시, 마트 기획전"),
                (9, "https://link.coupang.com/a/b69VkQ", "/image/9.png", "로켓프레시, 식단관리"),
                (10, "https://link.coupang.com/a/b69VsR", "/image/10.png", "로켓프레시, 가격역전"),

                (11, "https://link.coupang.com/a/b69Vwb", "/image/11.png", "홈인테리어, 공간별 인테리어 추천"),
                (12, "https://link.coupang.com/a/b69VGB", "/image/12.png", "로켓패션, 로켓배송 금주의 신상"),
                (13, "https://link.coupang.com/a/b69VKU", "/image/13.png", "가전디지털, 가성비 게이밍 모니터"),
                (14, "https://link.coupang.com/a/b69VOH", "/image/14.png", "가전디지털, 갤럭시 버즈"),
                (15, "https://link.coupang.com/a/b69VU1", "/image/15.png", "가전디지털, 프리미엄 게이밍 노트북"),

                (16, "https://link.coupang.com/a/b69V3V", "/image/16.png", "가전디지털, 게이밍 노트북"),
                (17, "https://link.coupang.com/a/b69V6U", "/image/17.png", "가전/디지털, 프리미엄 오디오"),
                (18, "https://link.coupang.com/a/b69Wb9", "/image/18.png", "로켓패션, 반품 마켓"),
                (19, "https://link.coupang.com/a/b69WhM", "/image/19.png", "쿠팡트래블, 매일 만나는 여행 특가"),
                (20, "https://link.coupang.com/a/b69Wlr", "/image/20.png", "도서/문구, 책 한잔")
            };

            var random = new Random();

            ViewBag.Data = data.OrderBy(row => random.Next()).ToArray(); ;

            return View();
        }

        // 골드박스
        [HttpGet("/GoldBox")]
        public async Task<IActionResult> GoldBox()
        {
            CoupangModel coupangModel = new CoupangModel(_coupangPartners);
            Product.Response itemList = await coupangModel.GetGoldBoxProduct();

            return View(itemList);
        }

        // 인가상품
        [HttpGet("/category/{id}")]
        public async Task<IActionResult> Category([FromRoute] int id)
        {
            // Enum을 이용한 유효성 검사
            if (!Enum.IsDefined(typeof(Request.Categories), id))
            {
                return BadRequest("잘못된 접근입니다.");
            }

            CoupangModel coupangModel = new CoupangModel(_coupangPartners);
            Product.Response itemList = await coupangModel.GetCategoryProduct(id);

            // 현재 카테고리 이름 조회
            var category = (Request.Categories)id;
            var categoryName = category.GetDisplayName();

            ViewBag.CategoryName = categoryName;

            return View(itemList);
        }

        // 쿠팡PL
        [HttpGet("/pl/{id}")]
        public async Task<IActionResult> Pl([FromRoute] int id)
        {
            // Enum을 이용한 유효성 검사
            if (!Enum.IsDefined(typeof(Request.Brand), id))
            {
                return BadRequest("잘못된 접근입니다.");
            }

            CoupangModel coupangModel = new CoupangModel(_coupangPartners);
            Product.Response itemList = await coupangModel.GetPlProduct(id);

            // 현재 PL 이름 조회
            var pl = (Request.Brand)id;
            var plName = pl.GetDisplayName();

            ViewBag.PlName = plName;

            return View(itemList);
        }

        // 상품 검색
        [HttpGet("/search")]
        public async Task<IActionResult> Search(string? keyword)
        {
            // 검색어 처리 로직
            if (string.IsNullOrEmpty(keyword))
            {
                return BadRequest("검색어를 입력해주세요.");
            }

            CoupangModel coupangModel = new CoupangModel(_coupangPartners);
            Search.Response itemList = await coupangModel.GetSearchProduct(keyword);

            ViewBag.Keyword = keyword;

            // 검색 키워드를 DB에 저장
            await _context.SearchKeyword.AddAsync(new SearchKeyword { 
                Keyword = keyword,
                IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                UserAgent = Request.Headers["User-Agent"],
                CreatedAt = DateTime.Now
            });
            await _context.SaveChangesAsync();

            return View(itemList);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}