// @ts-nocheck
import { Request, Response } from 'express';
import asyncHandler from '../utils/asyncHandler';
import ApiError from '../utils/apiError';
import ApiResponse from '../utils/apiResponse';
import prisma from '../DB/db';

// fetch user cart item
export const getUserCartItem = asyncHandler(
  async (req: Request, res: Response): Promise<unknown> => {
    const { id } = req.params;

    if (!id) {
      throw new ApiError(false, 400, 'User id is required');
    }

    const getAllCartItems = await prisma.cart.findMany({
      where: {
        userId: id,
      },
      include: {
        items: {
          include: {
            product: true,
            productVariant: true,
          },
        },
      },
    });

    return res.status(200).json(
      new ApiResponse(true, 200, 'Fetched all users Cart Items successfully', {
        getAllCartItems,
      })
    );
  }
);

// Add to Cart
export const addToCart = async (req: Request, res: Response) => {
  try {
    const { userId, productId, variantId, quantity } = req.body;

    if (!userId || !productId || !quantity) {
      return res.status(400).json({ message: 'Missing required fields' });
    }

    // Find or create user's cart
    let cart = await prisma.cart.findUnique({
      where: { userId },
    });

    if (!cart) {
      cart = await prisma.cart.create({
        data: {
          userId,
        },
      });
    }

    // Check if the product (and variant) already exists in cart
    const existingItem = await prisma.cartItem.findFirst({
      where: {
        cartId: cart.id,
        productId,
        variantId: variantId,
      },
    });

    if (existingItem) {
      // Increment quantity
      const updatedItem = await prisma.cartItem.update({
        where: { id: existingItem.id },
        data: { quantity: existingItem.quantity + quantity },
      });
      return res.status(200).json({ message: 'Cart updated', item: updatedItem });
    } else {
      // Add new cart item
      const newItem = await prisma.cartItem.create({
        data: {
          cartId: cart.id,
          productId,
          variantId: variantId || null,
          quantity,
        },
      });
      return res.status(201).json({ message: 'Added to cart', item: newItem });
    }
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: 'Something went wrong' });
  }
};

// --- Remove Item ---
export const removeItem = asyncHandler(async (req: Request, res: Response) => {
  const { itemId } = req.params;

  await prisma.cartItem.delete({
    where: { id: itemId },
  });

  return res.status(200).json(new ApiResponse(true, 200, 'Item removed'));
});



// get cart item count
export const getCartItemCount = async (req: Request, res: Response) => {
try {
    const { id } = req.params; // userId from params

    if (!id) {
      return res.status(400).json({
        success: false,
        message: "User ID is required",
        items: [],
      });
    }

    // Find cart for the user
    const cart = await prisma.cart.findUnique({
      where: { userId: id },
      include: { items: true }, // assumes `items` has `id` field
    });

    // If no cart found, return empty array
    if (!cart) {
      return res.status(200).json({
        success: true,
        message: "Cart is empty",
        items: [],
      });
    }

    // Extract item IDs
    const itemIds = cart.items.map(item => item.id);

    return res.status(200).json({
      success: true,
      message: "Cart items fetched successfully",
      items: itemIds,
    });
  } catch (error) {
    console.error("Error fetching cart items:", error);
    return res.status(500).json({
      success: false,
      message: "Server error",
      items: [],
    });
  }
};




// ---------------- INCREMENT CART ITEM QUANTITY ----------------
export const incrementCartItem = async (req, res) => {
  try {
    const { cartItemId } = req.params; // ID of the cart item to increment

    if (!cartItemId) {
      return res.status(400).json({
        success: false,
        message: "Cart item ID is required",
      });
    }

    // Find the cart item
    const cartItem = await prisma.cartItem.findUnique({
      where: { id: cartItemId },
      include: { productVariant: true }, // get stock info
    });

    if (!cartItem) {
      return res.status(404).json({
        success: false,
        message: "Cart item not found",
      });
    }

    // Check stock
    if (cartItem.quantity >= (cartItem.productVariant?.stock ?? 0)) {
      return res.status(400).json({
        success: false,
        message: "Cannot increase quantity. Stock limit reached.",
      });
    }

    // Increment quantity
    const updatedCartItem = await prisma.cartItem.update({
      where: { id: cartItemId },
      data: { quantity: cartItem.quantity + 1 },
    });

    return res.status(200).json({
      success: true,
      message: "Quantity increased",
      cartItem: updatedCartItem,
    });
  } catch (error) {
    console.error("Error incrementing cart item:", error);
    return res.status(500).json({
      success: false,
      message: "Server error",
    });
  }
};

// ---------------- DECREMENT CART ITEM QUANTITY ----------------
export const decrementCartItem = async (req, res) => {
  try {
    const { cartItemId } = req.params;

    if (!cartItemId) {
      return res.status(400).json({
        success: false,
        message: "Cart item ID is required",
      });
    }

    const cartItem = await prisma.cartItem.findUnique({
      where: { id: cartItemId },
    });

    if (!cartItem) {
      return res.status(404).json({
        success: false,
        message: "Cart item not found",
      });
    }

    if (cartItem.quantity <= 1) {
      return res.status(400).json({
        success: false,
        message: "Quantity cannot be less than 1",
      });
    }

    const updatedCartItem = await prisma.cartItem.update({
      where: { id: cartItemId },
      data: { quantity: cartItem.quantity - 1 },
    });

    return res.status(200).json({
      success: true,
      message: "Quantity decreased",
      cartItem: updatedCartItem,
    });
  } catch (error) {
    console.error("Error decrementing cart item:", error);
    return res.status(500).json({
      success: false,
      message: "Server error",
    });
  }
};