"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateCoupon = exports.syncCartItem = exports.getCart = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
// Get or Create User Shopping Cart
const getCart = async (req, res) => {
    try {
        const userId = req.user?.userId;
        if (!userId)
            return (0, response_utils_1.sendError)(res, 'User ID missing', null, 401);
        let cart = await database_1.default.shoppingCart.findUnique({
            where: { userId },
            include: {
                items: {
                    include: {
                        variant: true,
                        book: {
                            include: {
                                bookAuthors: { include: { author: true } },
                                variants: { where: { isActive: true } },
                            },
                        },
                    },
                },
            },
        });
        if (!cart) {
            cart = await database_1.default.shoppingCart.create({
                data: { userId },
                include: {
                    items: {
                        include: {
                            variant: true,
                            book: {
                                include: {
                                    bookAuthors: { include: { author: true } },
                                    variants: { where: { isActive: true } },
                                },
                            },
                        },
                    },
                },
            });
        }
        return (0, response_utils_1.sendSuccess)(res, 'User cart retrieved', cart);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error fetching cart', error.message, 500);
    }
};
exports.getCart = getCart;
// Add / Sync Item to User Cart
const syncCartItem = async (req, res) => {
    try {
        const userId = req.user?.userId;
        const { bookId, variantId, quantity } = req.body;
        if (!userId)
            return (0, response_utils_1.sendError)(res, 'Unauthorized', null, 401);
        let cart = await database_1.default.shoppingCart.findUnique({ where: { userId } });
        if (!cart) {
            cart = await database_1.default.shoppingCart.create({ data: { userId } });
        }
        const existingItem = await database_1.default.cartItem.findFirst({
            where: {
                cartId: cart.id,
                bookId,
                ...(variantId ? { variantId } : { variantId: null }),
            },
        });
        if (quantity <= 0) {
            if (existingItem) {
                await database_1.default.cartItem.delete({ where: { id: existingItem.id } });
            }
            return (0, response_utils_1.sendSuccess)(res, 'Item removed from cart');
        }
        if (existingItem) {
            await database_1.default.cartItem.update({
                where: { id: existingItem.id },
                data: { quantity: Number(quantity) },
            });
        }
        else {
            await database_1.default.cartItem.create({
                data: {
                    cartId: cart.id,
                    bookId,
                    variantId: variantId || null,
                    quantity: Number(quantity),
                },
            });
        }
        return (0, response_utils_1.sendSuccess)(res, 'Cart item synced successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to sync cart item', error.message, 500);
    }
};
exports.syncCartItem = syncCartItem;
// Validate Coupon Code
const validateCoupon = async (req, res) => {
    try {
        const { code, subtotal } = req.body;
        const coupon = await database_1.default.coupon.findUnique({
            where: { code: String(code).toUpperCase() },
        });
        if (!coupon || !coupon.isActive || coupon.expiresAt < new Date()) {
            return (0, response_utils_1.sendError)(res, 'Invalid or expired coupon code', null, 400);
        }
        if (coupon.minOrderValue && Number(subtotal) < Number(coupon.minOrderValue)) {
            return (0, response_utils_1.sendError)(res, `Minimum order value of ₹${coupon.minOrderValue} required for coupon '${code}'`, null, 400);
        }
        return (0, response_utils_1.sendSuccess)(res, 'Coupon code applied successfully!', {
            code: coupon.code,
            discountType: coupon.discountType,
            discountValue: Number(coupon.discountValue),
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Coupon validation failed', error.message, 500);
    }
};
exports.validateCoupon = validateCoupon;
//# sourceMappingURL=cart.controller.js.map