const { sequelize, Book, Review } = require('../models');

async function syncRatings() {
    try {
        console.log("Starting rating sync...");
        const books = await Book.findAll({
            include: [{ model: Review }] // Fetch reviews for each book
        });

        console.log(`Found ${books.length} books.`);

        for (const book of books) {
            const reviews = book.Reviews || [];
            const reviewCount = reviews.length;

            let newRating = 0;
            if (reviewCount > 0) {
                const totalRating = reviews.reduce((sum, r) => sum + r.rating, 0);
                newRating = parseFloat((totalRating / reviewCount).toFixed(1));
            }

            // Only update if different
            if (parseFloat(book.rating) !== newRating) {
                console.log(`Updating Book "${book.title}": ${book.rating} -> ${newRating} (${reviewCount} reviews)`);
                await book.update({ rating: newRating });
            } else {
                console.log(`Book "${book.title}" is already correct: ${newRating} (${reviewCount} reviews)`);
            }
        }

        console.log("Rating sync completed successfully.");
    } catch (error) {
        console.error("Error syncing ratings:", error);
    } finally {
        await sequelize.close();
    }
}

syncRatings();
