const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const { protect } = require("../middleware/auth");
const Cart = require("../models/Cart");
const Product = require("../models/Product");

/**
 * @desc    Get current user's cart
 * @route   GET /api/cart
 * @access  Private
 */
router.get("/", protect, async (req, res) => {
  try {
    const cart = await Cart.findOne({ user: req.user._id }).populate("items.product");
    if (!cart) {
      return res.status(200).json({ success: true, cart: { items: [], totalItems: 0, totalPrice: 0 } });
    }
    res.status(200).json({ success: true, cart });
  } catch (error) {
    console.error("Get Cart Error:", error);
    res.status(500).json({ success: false, error: "Server Error" });
  }
});

/**
 * @desc    Get all carts (admin/debugging)
 * @route   GET /api/cart/all
 * @access  Private/Admin
 */
router.get("/all", protect, async (req, res) => {
  try {
    const carts = await Cart.find().populate("user").populate("items.product");
    res.status(200).json({ success: true, carts });
  } catch (error) {
    console.error("Get All Carts Error:", error);
    res.status(500).json({ success: false, error: "Server Error" });
  }
});

/**
 * @desc    Add item to cart
 * @route   POST /api/cart
 * @access  Private
 */
router.post("/", protect, async (req, res) => {
  try {
    const { productId, quantity = 1, color, size } = req.body;
    const qty = Number(quantity);

    if (!mongoose.Types.ObjectId.isValid(productId)) {
      return res.status(400).json({ success: false, error: "Invalid productId" });
    }

    const product = await Product.findById(productId);
    if (!product) {
      return res.status(404).json({ success: false, error: "Product not found" });
    }

    let cart = await Cart.findOne({ user: req.user._id });
    if (!cart) {
      cart = new Cart({ user: req.user._id, items: [] });
    }

    const existingItem = cart.items.find(
      (item) =>
        item.product.toString() === productId &&
        item.color === color &&
        item.size === size
    );

    if (existingItem) {
      existingItem.quantity += qty;
    } else {
      cart.items.push({
        product: product._id,
        quantity: qty,
        color: color || null,
        size: size || null,
        price: product.price || 0,
      });
    }

    await cart.save();
    res.status(200).json({ success: true, cart });
  } catch (error) {
    console.error("Add Cart Error:", error);
    res.status(500).json({ success: false, error: "Server Error" });
  }
});

/**
 * @desc    Update item quantity in cart
 * @route   PUT /api/cart/:id  (productId or cartItemId)
 * @access  Private
 */
router.put("/:id", protect, async (req, res) => {
  try {
    const { quantity, color, size } = req.body;

    let cart = await Cart.findOne({ user: req.user._id });
    if (!cart) return res.status(404).json({ success: false, error: "Cart not found" });

    let item =
      cart.items.find(
        (i) =>
          i.product.toString() === req.params.id &&
          i.color === color &&
          i.size === size
      ) || cart.items.id(req.params.id);

    if (!item) {
      return res.status(404).json({ success: false, error: "Item not found in cart" });
    }

    item.quantity = quantity;
    await cart.save();

    res.status(200).json({ success: true, cart });
  } catch (error) {
    console.error("Update Cart Error:", error);
    res.status(500).json({ success: false, error: "Server Error" });
  }
});

/**
 * @desc    Remove item from cart
 * @route   DELETE /api/cart/:productId?color=Black&size=M
 * @access  Private
 */
router.delete("/:productId", protect, async (req, res) => {
  try {
    const { color, size } = req.query;

    let cart = await Cart.findOne({ user: req.user._id });
    if (!cart) return res.status(404).json({ success: false, error: "Cart not found" });

    cart.items = cart.items.filter(
      (item) =>
        !(
          item.product.toString() === req.params.productId &&
          item.color === color &&
          item.size === size
        )
    );

    cart.totalItems = cart.items.reduce((acc, item) => acc + item.quantity, 0);
    cart.totalPrice = cart.items.reduce((acc, item) => acc + item.price * item.quantity, 0);

    await cart.save();
    res.status(200).json({ success: true, cart });
  } catch (error) {
    console.error("Delete Cart Error:", error);
    res.status(500).json({ success: false, error: "Server Error" });
  }
});

module.exports = router;
