"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFavorites = getFavorites;
exports.addFavorite = addFavorite;
exports.removeFavorite = removeFavorite;
exports.isFavorited = isFavorited;
const client_1 = require("@prisma/client");
const prisma = new client_1.PrismaClient();
/**
 * 获取用户收藏列表（收藏的是书籍）
 */
async function getFavorites(userId) {
    const userIdNum = parseInt(userId);
    const favorites = await prisma.favorite.findMany({
        where: { userId: userIdNum },
        include: {
            book: {
                select: {
                    id: true,
                    title: true,
                    subtitle: true,
                    description: true,
                    coverUrl: true,
                    createdAt: true,
                },
            },
        },
        orderBy: { createdAt: 'desc' },
    });
    return favorites;
}
/**
 * 添加收藏（收藏书籍）
 */
async function addFavorite(userId, bookId) {
    const userIdNum = parseInt(userId);
    // 检查是否已存在
    const existing = await prisma.favorite.findUnique({
        where: {
            userId_bookId: {
                userId: userIdNum,
                bookId,
            },
        },
    });
    if (existing) {
        return existing;
    }
    return await prisma.favorite.create({
        data: {
            userId: userIdNum,
            bookId,
        },
        include: {
            book: {
                select: {
                    id: true,
                    title: true,
                    subtitle: true,
                    description: true,
                    coverUrl: true,
                    createdAt: true,
                },
            },
        },
    });
}
/**
 * 取消收藏
 */
async function removeFavorite(userId, bookId) {
    const userIdNum = parseInt(userId);
    return await prisma.favorite.delete({
        where: {
            userId_bookId: {
                userId: userIdNum,
                bookId,
            },
        },
    });
}
/**
 * 检查是否已收藏
 */
async function isFavorited(userId, bookId) {
    const userIdNum = parseInt(userId);
    const favorite = await prisma.favorite.findUnique({
        where: {
            userId_bookId: {
                userId: userIdNum,
                bookId,
            },
        },
    });
    return !!favorite;
}
