"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WishlistService = void 0;
const database_1 = __importDefault(require("../config/database"));
class WishlistService {
    /**
     * Get or create a wishlist for a specific user
     */
    static async getOrCreateWishlist(userId) {
        let wishlist = await database_1.default.wishlist.findUnique({
            where: { userId },
        });
        if (!wishlist) {
            wishlist = await database_1.default.wishlist.create({
                data: { userId },
            });
        }
        return wishlist;
    }
    /**
     * Fetch user's wishlist with full book relations
     */
    static async getUserWishlist(userId) {
        const wishlist = await this.getOrCreateWishlist(userId);
        const items = await database_1.default.wishlistItem.findMany({
            where: { wishlistId: wishlist.id },
            include: {
                book: {
                    include: {
                        bookAuthors: { include: { author: true } },
                        bookCategories: { include: { category: true } },
                        images: { where: { isPrimary: true }, take: 1 },
                        variants: { where: { isActive: true } },
                    },
                },
            },
            orderBy: { createdAt: 'desc' },
        });
        const formattedItems = items.map((item) => ({
            id: item.id,
            wishlistId: item.wishlistId,
            bookId: item.bookId,
            createdAt: item.createdAt,
            book: {
                id: item.book.id,
                title: item.book.title,
                slug: item.book.slug,
                isbn: item.book.isbn,
                sku: item.book.sku,
                price: Number(item.book.price),
                discountPrice: item.book.discountPrice ? Number(item.book.discountPrice) : null,
                stock: item.book.stock,
                coverImage: item.book.coverImage || item.book.images[0]?.url || null,
                authorName: item.book.bookAuthors[0]?.author.name || 'Indian Author',
                categoryName: item.book.bookCategories[0]?.category.name || 'General',
                format: item.book.format,
                inStock: item.book.stock > 0,
                variantsCount: item.book.variants.length,
            },
        }));
        return {
            wishlistId: wishlist.id,
            userId,
            items: formattedItems,
            count: formattedItems.length,
        };
    }
    /**
     * Toggle a book in the user's wishlist (Add if not present, Remove if present)
     */
    static async toggleWishlistItem(userId, bookId) {
        // Verify book exists
        const book = await database_1.default.book.findUnique({ where: { id: bookId } });
        if (!book) {
            throw new Error('Book not found in store catalog');
        }
        const wishlist = await this.getOrCreateWishlist(userId);
        const existingItem = await database_1.default.wishlistItem.findUnique({
            where: {
                wishlistId_bookId: {
                    wishlistId: wishlist.id,
                    bookId,
                },
            },
        });
        let isInWishlist = false;
        let message = '';
        if (existingItem) {
            // Remove item
            await database_1.default.wishlistItem.delete({
                where: { id: existingItem.id },
            });
            isInWishlist = false;
            message = `Removed “${book.title}” from your wishlist`;
        }
        else {
            // Add item
            await database_1.default.wishlistItem.create({
                data: {
                    wishlistId: wishlist.id,
                    bookId,
                },
            });
            isInWishlist = true;
            message = `Added “${book.title}” to your wishlist`;
        }
        const count = await database_1.default.wishlistItem.count({
            where: { wishlistId: wishlist.id },
        });
        return {
            isInWishlist,
            message,
            bookId,
            count,
        };
    }
    /**
     * Explicitly remove a book from the wishlist
     */
    static async removeWishlistItem(userId, bookId) {
        const wishlist = await database_1.default.wishlist.findUnique({ where: { userId } });
        if (!wishlist) {
            return { success: true, count: 0 };
        }
        await database_1.default.wishlistItem.deleteMany({
            where: {
                wishlistId: wishlist.id,
                OR: [{ bookId }, { id: bookId }],
            },
        });
        const count = await database_1.default.wishlistItem.count({
            where: { wishlistId: wishlist.id },
        });
        return {
            success: true,
            message: 'Item removed from wishlist',
            count,
        };
    }
    /**
     * Get total item count in user's wishlist
     */
    static async getWishlistCount(userId) {
        const wishlist = await database_1.default.wishlist.findUnique({ where: { userId } });
        if (!wishlist)
            return 0;
        return database_1.default.wishlistItem.count({
            where: { wishlistId: wishlist.id },
        });
    }
    /**
     * Clear all items in user's wishlist
     */
    static async clearWishlist(userId) {
        const wishlist = await database_1.default.wishlist.findUnique({ where: { userId } });
        if (!wishlist)
            return { count: 0 };
        await database_1.default.wishlistItem.deleteMany({
            where: { wishlistId: wishlist.id },
        });
        return { count: 0, message: 'Wishlist cleared successfully' };
    }
}
exports.WishlistService = WishlistService;
//# sourceMappingURL=wishlist.service.js.map