﻿using KernelRecordsMVC.Infrastructure.Data;
using KernelRecordsMVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace KernelRecordsMVC.Web.Controllers;

public class WishlistController : Controller
{
    private readonly KernelRecordsContext _context;

    public WishlistController(KernelRecordsContext context)
    {
        _context = context;
    }

    // ==========================================
    // WISHLIST
    // ==========================================

    [HttpGet]
    public IActionResult Index()
    {
        var userId = GetUserId();

        if (userId == null)
        {
            return RedirectToAction(
                "Login",
                "Account");
        }

        var wishlist = _context.Wishlists
            .Include(w => w.WishlistProducts)
                .ThenInclude(wp => wp.Product)
                    .ThenInclude(p => p.Release)
            .FirstOrDefault(w => w.UserId == userId.Value);

        if (wishlist == null)
        {
            return View(new Wishlist());
        }

        return View(wishlist);
    }


    // ==========================================
    // ADD TO WISHLIST
    // ==========================================

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Add(long productId)
    {
        var sessionUserId =
            HttpContext.Session.GetInt32("UserId");

        if (!sessionUserId.HasValue)
        {
            return RedirectToAction(
                "Login",
                "Account");
        }

        var userId =
            (long)sessionUserId.Value;


        var product =
            _context.Products
                .FirstOrDefault(p =>
                    p.ProductId == productId);

        if (product == null)
            return NotFound();


        var wishlist =
            _context.Wishlists
                .FirstOrDefault(w =>
                    w.UserId == userId);


        // Create wishlist if user doesn't have one yet.
        if (wishlist == null)
        {
            wishlist = new Wishlist
            {
                WishlistId =
                    GetNextWishlistId(),

                UserId =
                    userId
            };


            _context.Wishlists.Add(
                wishlist);

            _context.SaveChanges();
        }


        // Prevent duplicate product.
        var alreadyExists =
            _context.WishlistProducts
                .Any(wp =>
                    wp.WishlistId ==
                    wishlist.WishlistId &&
                    wp.ProductId ==
                    productId);


        if (!alreadyExists)
        {
            var wishlistProduct =
                new WishlistProduct
                {
                    WishlistId =
                        wishlist.WishlistId,

                    ProductId =
                        productId
                };


            _context.WishlistProducts.Add(
                wishlistProduct);

            _context.SaveChanges();
        }


        TempData["Success"] =
            "Product added to your wishlist.";


        return RedirectToAction(
            nameof(Index));
    }


    // ==========================================
    // REMOVE FROM WISHLIST
    // ==========================================

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Remove(long productId)
    {
        var userId = GetUserId();

        if (userId == null)
        {
            return RedirectToAction(
                "Login",
                "Account");
        }

        var item = _context.WishlistProducts
            .Include(x => x.Wishlist)
            .FirstOrDefault(x =>
                x.ProductId == productId &&
                x.Wishlist.UserId == userId.Value);

        if (item != null)
        {
            _context.WishlistProducts.Remove(item);
            _context.SaveChanges();

            TempData["Success"] =
                "Product removed from your wishlist.";
        }

        return RedirectToAction(nameof(Index));
    }


    // ==========================================
    // MOVE WISHLIST PRODUCT TO CART
    // ==========================================

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddToCart(long productId)
    {
        var userId = GetUserId();

        if (userId == null)
        {
            return RedirectToAction(
                "Login",
                "Account");
        }

        var product = _context.Products
            .Include(p => p.Release)
            .FirstOrDefault(p => p.ProductId == productId);

        if (product == null)
            return NotFound();

        if (product.Stock <= 0)
        {
            TempData["Error"] =
                "This product is currently out of stock.";

            return RedirectToAction(nameof(Index));
        }

        return RedirectToAction(
            "AddProduct",
            "Order",
            new { id = productId });
    }


    // ==========================================
    // USER ID
    // ==========================================

    private long? GetUserId()
    {
        var userId = HttpContext.Session.GetInt32("UserId");

        if (userId.HasValue)
            return userId.Value;

        return null;
    }


    // ==========================================
    // WISHLIST ID
    // ==========================================

    private long GetNextWishlistId()
    {
        var maxId = _context.Wishlists
            .Select(x => (long?)x.WishlistId)
            .Max();

        return (maxId ?? 0) + 1;
    }
}