const DetailSellerReviews = require("../models/DetailSellerReviews");
const errorHandler = require("../util/errorHandler");


exports.addSellerRating = (req, res, next) => {
    const { sellerId } = req.params;
    const { rate, review } = req.body;

    const customerId = req.customerId; // Auto-fetched customerId from token

    if (!customerId || !rate) {
        return errorHandler("Customer ID or rate is missing from the request!", 400);
    }

    DetailSellerReviews.findOne({
        where: {
            seller_id: sellerId,
            customer_id: customerId,
        },
    })
    .then((existingReview) => {
        if(existingReview) {
            return errorHandler("Rating already exists for this customer and seller.", 400);
        }

        return DetailSellerReviews.create({
            seller_id: sellerId,
            customer_id: customerId,
            rate: rate,
            reviews: review,
            timestamp: new Date(),
        });
    })
    .then(() => {
        res.status(201).json({ success: true });
    })
    .catch((err) => {
        next(err);
    });
};
