const mongoose = require("mongoose");
const reviewModel = require("../models/reviews");

const addReview = async (req) => {
    const newReview = new reviewModel(req.body);
    const result = await newReview.save();
    return result
};

const getReviewsByShopId = async (req) => {
    const { shopId, stars } = req.query;
    const filter = { shopId };
    if( stars !== undefined && stars !== null && stars !== ""){
        filter.stars = stars
    };
    
    const review = await reviewModel.find(filter).populate({
        path: "userId",
        select: "fullName profileImage"
    })
    return review;
};

const getReviewsByProduct = async (req) => {
    const { productId, stars } = req.query;
    const filter = { productId };
    if( stars !== undefined && stars !== null && stars !== ""){
        filter.stars = stars
    };

    const review = await reviewModel.find(filter).populate({
        path: "userId",
        select: "fullName profileImage"
    })
    return review
};

const overAllShopReviews = async (req) => {
    const { shopId } = req.body;
    const totalCount = await reviewModel.find({shopId: shopId}).countDocuments();
    const result = await reviewModel.aggregate([
        { $match: {shopId: new mongoose.Types.ObjectId(shopId)}},
        {
            $group:{
                _id: "$shopId",
                averageRating: {$avg: "$stars"}
            }
        }
    ]);

    const avgRating = result.length > 0 ? result[0].averageRating.toFixed(1): null;
    const data = {
        avgRating,
        totalCount
    };
    return data
};

const overAllProductReviews = async (req) => {
    const { productId } = req.query;
    const result = await reviewModel.aggregate([
        { $match: { productId: new mongoose.Types.ObjectId(productId)}},
        {
            $group: {
                _id: "$productId",
                averageRating: { $avg: "$stars"}
            }
        }
    ]);
    const avgRating = result.length > 0 ? result[0].averageRating.toFixed(1): null;
    return avgRating;
};

const overAllReviews = async (req) => {
    const { adminId } = req.query 

    const totalCount = await reviewModel.find({ adminId: adminId }).countDocuments();
    const result = await reviewModel.aggregate([
        { $match: { adminId: new mongoose.Types.ObjectId(adminId) }},
        {
            $group: {
                _id: "$adminId",
                averageRating: { $avg: "$stars"}
            }
        }
    ]);
    const avgRating = result.length > 0 ? result[0].averageRating.toFixed(1): null;
    const data = {
        avgRating,
        totalCount
    }
    return data
};

const deleteReview = async (req) => {
    const { reviewId } = req.query;
    const result = await reviewModel.findByIdAndDelete({_id: reviewId});
    return result;
};

module.exports = {
    addReview,
    getReviewsByShopId,
    getReviewsByProduct,
    overAllShopReviews,
    overAllProductReviews,
    overAllReviews,
    deleteReview
};