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

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

const getReviewById = async (req) => {
    const { reviewId } = req.query;

    const review = await reviewModel.findById({_id: reviewId}).populate("userId");
    return review
};

const getAllReviews = async (req) => {
    const { userId, technicianId, star } = req.query;
    const filter = {};

    if(userId){
        filter.userId = userId
    };
    if(technicianId){
        filter.technicianId = technicianId
    }
    if(star){
        filter.star = star
    };

    const reviews = await reviewModel.find(filter).populate("userId");
    return reviews
};

const deleteReview = async (req) => {
    const { reviewId } = req.body;
    const review = await reviewModel.findByIdAndDelete(reviewId);
    return review
};

const updateReview = async (req) => {
    const { reviewId } = req.body;
    const udpatedData = req.body;

    const review = await reviewModel.findByIdAndUpdate(reviewId, 
        { $set: udpatedData },
        { new: true }
    );
    return review
};

const avgTechnicianRating = async (req) => {
    const { technicianId } = req.body;
    const result = await reviewModel.aggregate([
        { $match: {technicianId: new mongoose.Types.ObjectId(technicianId)}},
        {
            $group: {
                _id: "$technicianId",
                averageRating: {$avg: "$star" }
            }
        }
    ]);
    const avgRating = result.length > 0 && result[0].averageRating !== null
    ? result[0].averageRating.toFixed(1)
    : null;
    const totalCount = await reviewModel.countDocuments({technicianId: technicianId});
    const data = {
        avgRating,
        totalCount
    };
    return data
    return
};

module.exports = {
    createReview,
    getReviewById,
    getAllReviews,
    deleteReview,
    updateReview,
    avgTechnicianRating
};