"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.moderateReview = exports.adminReplyToReview = exports.voteHelpfulReview = exports.getBookReviews = exports.createReview = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
// Simple Spam Detection filter
const containsSpamOrProfanity = (text) => {
    const forbidden = ['casino', 'viagra', 'crypto-scam', 'free-money', 'hack-pass'];
    const lower = text.toLowerCase();
    return forbidden.some((word) => lower.includes(word));
};
// 1. Submit New Customer Review
const createReview = async (req, res) => {
    try {
        const userId = req.user?.userId;
        if (!userId)
            return (0, response_utils_1.sendError)(res, 'Unauthorized', null, 401);
        const { bookId, rating, title, comment, images = [] } = req.body;
        // Check if user has purchased this book (Verified Purchase check)
        const userOrder = await database_1.default.order.findFirst({
            where: {
                userId,
                status: { in: ['DELIVERED', 'SHIPPED', 'CONFIRMED'] },
                items: { some: { bookId } },
            },
        });
        const isVerifiedPurchase = !!userOrder;
        // Automated Spam Detection
        const isSpam = containsSpamOrProfanity(comment) || (title && containsSpamOrProfanity(title));
        const isApproved = !isSpam; // Auto-flag spam for moderation
        const review = await database_1.default.review.create({
            data: {
                bookId,
                userId,
                rating: Number(rating),
                title,
                comment,
                isVerifiedPurchase,
                isApproved,
                isFlagged: isSpam,
                images,
            },
            include: {
                user: { select: { firstName: true, lastName: true, avatarUrl: true } },
            },
        });
        // Re-calculate Book Average Rating
        const agg = await database_1.default.review.aggregate({
            where: { bookId, isApproved: true },
            _avg: { rating: true },
            _count: { rating: true },
        });
        const newAvg = agg._avg.rating ? Number(agg._avg.rating.toFixed(2)) : rating;
        const newCount = agg._count.rating || 1;
        await database_1.default.book.update({
            where: { id: bookId },
            data: {
                ratingAverage: newAvg,
                ratingCount: newCount,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, isSpam ? 'Review submitted and sent for moderation.' : 'Review published successfully!', review, 201);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to submit review', error.message, 500);
    }
};
exports.createReview = createReview;
// 2. Get Book Reviews & Rating Analytics Breakdown
const getBookReviews = async (req, res) => {
    try {
        const { bookId } = req.params;
        const { page = 1, limit = 10, ratingFilter } = req.query;
        const take = Number(limit);
        const skip = (Number(page) - 1) * take;
        const where = { bookId, isApproved: true };
        if (ratingFilter)
            where.rating = Number(ratingFilter);
        const [reviews, total, ratingCounts] = await Promise.all([
            database_1.default.review.findMany({
                where,
                take,
                skip,
                include: {
                    user: { select: { id: true, firstName: true, lastName: true, avatarUrl: true } },
                },
                orderBy: { createdAt: 'desc' },
            }),
            database_1.default.review.count({ where }),
            database_1.default.review.groupBy({
                by: ['rating'],
                where: { bookId, isApproved: true },
                _count: { rating: true },
            }),
        ]);
        // Calculate rating percentages (5-star down to 1-star)
        const breakdown = { 5: 0, 4: 0, 3: 0, 2: 0, 1: 0 };
        let totalReviewsSum = 0;
        ratingCounts.forEach((r) => {
            breakdown[r.rating] = r._count.rating;
            totalReviewsSum += r._count.rating;
        });
        const percentages = {
            5: totalReviewsSum ? Math.round(((breakdown[5] || 0) / totalReviewsSum) * 100) : 0,
            4: totalReviewsSum ? Math.round(((breakdown[4] || 0) / totalReviewsSum) * 100) : 0,
            3: totalReviewsSum ? Math.round(((breakdown[3] || 0) / totalReviewsSum) * 100) : 0,
            2: totalReviewsSum ? Math.round(((breakdown[2] || 0) / totalReviewsSum) * 100) : 0,
            1: totalReviewsSum ? Math.round(((breakdown[1] || 0) / totalReviewsSum) * 100) : 0,
        };
        return (0, response_utils_1.sendSuccess)(res, 'Book reviews & analytics retrieved', {
            reviews,
            analytics: {
                totalReviews: totalReviewsSum,
                breakdown,
                percentages,
            },
            pagination: {
                total,
                page: Number(page),
                limit: take,
                totalPages: Math.ceil(total / take),
            },
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Error fetching reviews', error.message, 500);
    }
};
exports.getBookReviews = getBookReviews;
// 3. Upvote Helpful Review
const voteHelpfulReview = async (req, res) => {
    try {
        const { id } = req.params;
        const review = await database_1.default.review.update({
            where: { id },
            data: {
                helpfulVotes: { increment: 1 },
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Voted helpful successfully', { helpfulVotes: review.helpfulVotes });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to vote review', error.message, 500);
    }
};
exports.voteHelpfulReview = voteHelpfulReview;
// 4. Admin Reply to Review
const adminReplyToReview = async (req, res) => {
    try {
        const { id } = req.params;
        const { adminReply } = req.body;
        const review = await database_1.default.review.update({
            where: { id },
            data: { adminReply },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Admin reply published', review);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to reply to review', error.message, 500);
    }
};
exports.adminReplyToReview = adminReplyToReview;
// 5. Admin Moderation Queue (Approve / Flag / Delete)
const moderateReview = async (req, res) => {
    try {
        const { id } = req.params;
        const { isApproved, isFlagged } = req.body;
        const review = await database_1.default.review.update({
            where: { id },
            data: {
                ...(isApproved !== undefined && { isApproved }),
                ...(isFlagged !== undefined && { isFlagged }),
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Review moderation updated', review);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Moderation update failed', error.message, 500);
    }
};
exports.moderateReview = moderateReview;
//# sourceMappingURL=review.controller.js.map