"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrementCartItem = exports.incrementCartItem = exports.getCartItemCount = exports.removeItem = exports.addToCart = exports.getUserCartItem = void 0;
const asyncHandler_1 = __importDefault(require("../utils/asyncHandler"));
const apiError_1 = __importDefault(require("../utils/apiError"));
const apiResponse_1 = __importDefault(require("../utils/apiResponse"));
const db_1 = __importDefault(require("../DB/db"));
// fetch user cart item
exports.getUserCartItem = (0, asyncHandler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { id } = req.params;
    if (!id) {
        throw new apiError_1.default(false, 400, 'User id is required');
    }
    const getAllCartItems = yield db_1.default.cart.findMany({
        where: {
            userId: id,
        },
        include: {
            items: {
                include: {
                    product: true,
                    productVariant: true,
                },
            },
        },
    });
    return res.status(200).json(new apiResponse_1.default(true, 200, 'Fetched all users Cart Items successfully', {
        getAllCartItems,
    }));
}));
// Add to Cart
const addToCart = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    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 = yield db_1.default.cart.findUnique({
            where: { userId },
        });
        if (!cart) {
            cart = yield db_1.default.cart.create({
                data: {
                    userId,
                },
            });
        }
        // Check if the product (and variant) already exists in cart
        const existingItem = yield db_1.default.cartItem.findFirst({
            where: {
                cartId: cart.id,
                productId,
                variantId: variantId,
            },
        });
        if (existingItem) {
            // Increment quantity
            const updatedItem = yield db_1.default.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 = yield db_1.default.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' });
    }
});
exports.addToCart = addToCart;
// --- Remove Item ---
exports.removeItem = (0, asyncHandler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { itemId } = req.params;
    yield db_1.default.cartItem.delete({
        where: { id: itemId },
    });
    return res.status(200).json(new apiResponse_1.default(true, 200, 'Item removed'));
}));
// get cart item count
const getCartItemCount = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    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 = yield db_1.default.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: [],
        });
    }
});
exports.getCartItemCount = getCartItemCount;
// ---------------- INCREMENT CART ITEM QUANTITY ----------------
const incrementCartItem = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    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 = yield db_1.default.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 >= ((_b = (_a = cartItem.productVariant) === null || _a === void 0 ? void 0 : _a.stock) !== null && _b !== void 0 ? _b : 0)) {
            return res.status(400).json({
                success: false,
                message: "Cannot increase quantity. Stock limit reached.",
            });
        }
        // Increment quantity
        const updatedCartItem = yield db_1.default.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",
        });
    }
});
exports.incrementCartItem = incrementCartItem;
// ---------------- DECREMENT CART ITEM QUANTITY ----------------
const decrementCartItem = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { cartItemId } = req.params;
        if (!cartItemId) {
            return res.status(400).json({
                success: false,
                message: "Cart item ID is required",
            });
        }
        const cartItem = yield db_1.default.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 = yield db_1.default.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",
        });
    }
});
exports.decrementCartItem = decrementCartItem;
