const userModel = require("../models/user");
const favoriteModel = require("../models/favorite");

const addToFavourites = async (req) => {
    const { technicianId, userId } = req.body;
    const technician = await userModel.findById({_id: technicianId});
    if(technician.favouriteBy.includes(userId)){
        const favroiteTechnician = await userModel.findByIdAndUpdate(technicianId, 
            { $pull: { favouriteBy: userId }},
            { new: true }
        );
        const favorite = await favoriteModel.findOneAndDelete({technicianId, userId});
        console.log(" Removed From Favorites!");
    } else {
        const favroiteTechnician = await userModel.findByIdAndUpdate(technicianId, 
            { $push: { favouriteBy: userId }},
            { new: true }
        );
        const newFavorite = new favoriteModel({
            userId: userId,
            technicianId: technicianId
        });
        const result = await newFavorite.save();
        console.log("Added to Favorite!")
        return result;
        }
};

const getAllFavourites = async (req) => {
    const { userId } = req.query;
    const user = await favoriteModel.find({userId: userId}).populate({
        path: "technicianId",
        select: "-password",
        populate: {
            path: "service",
            model: "Service"
        }
    });
    return user;
};

module.exports = {
    addToFavourites,
    getAllFavourites
};