﻿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 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();


        // Find existing wishlist
        var wishlist = _context.Wishlists
            .Include(w => w.WishlistProducts)
            .FirstOrDefault(w =>
                w.UserId == userId.Value);


        // Create wishlist if user doesn't have one
        if (wishlist == null)
        {
            wishlist = new Wishlist
            {
                WishlistId = GetNextWishlistId(),
                UserId = userId.Value
            };

            _context.Wishlists.Add(wishlist);
            _context.SaveChanges();
        }


        // Check if product is already there
        var alreadyExists = wishlist.WishlistProducts
            .Any(x => x.ProductId == productId);

        if (!alreadyExists)
        {
            var wishlistProduct = new WishlistProduct
            {
                WishlistId = wishlist.WishlistId,
                ProductId = productId,
                AddedAt = DateTime.Today
            };

            _context.WishlistProducts.Add(wishlistProduct);
            _context.SaveChanges();

            TempData["Success"] =
                "Product added to your wishlist.";
        }
        else
        {
            TempData["Info"] =
                "This product is already in your wishlist.";
        }

        return RedirectToAction(
            "Details",
            "Release",
            new { id = product.ReleaseId });
    }


    // ==========================================
    // 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;
    }
}