const favouriteModel = require("../models/favourite");
const shopModel = require("../models/shopModel");
const productModel = require("../models/productModel"); 

const addToFavourite = async (req) => {
    const { userId, shopId, productId } = req.body;
    if(productId){
        const product = await productModel.findById(productId);
            console.log("first :", product);
        // return 
        if(product.favouriteBy.includes(userId)){
            const favouriteProduct = await productModel.findByIdAndUpdate(productId,
                { $pull: { favouriteBy: userId } },
                { new: true }
            );
            const favourite = await favouriteModel.findOneAndDelete({ userId, productId });
            console.log("Product Removed");
            return null;
        } else {
            const favourite = await productModel.findByIdAndUpdate(productId, 
                { $push: { favouriteBy: userId } },
                { new: true }
            );
            let newfavourite = new favouriteModel({
                userId,
                productId
            });
            let result = await newfavourite.save();
            console.log("Product Added To Favourites"); 
            return result 
        }
    } else if(shopId){
        const shop = await shopModel.findOne({ _id: shopId});
        if(shop.favouriteBy.includes(userId)){
            const favouriteShop = await shopModel.findByIdAndUpdate(shopId, 
                { $pull: {favouriteBy: userId} },
                { new: true}
            );
            const favourite = await favouriteModel.findOneAndDelete({userId, shopId});
            console.log("Removed!");
            return null
        } else {
                const favouriteShop = await shopModel.findByIdAndUpdate(shopId, 
                { $push : {favouriteBy: userId} },
                { new: true }
            );
            let newfavourite = new favouriteModel({
                userId,
                shopId
            });
            let result = await newfavourite.save();
            console.log("Shop Added To Favourites"); 
            return result 
        }
    }
    
};

const getAllFavourites = async (req) => {
    const { userId } = req.query;
    const result = await favouriteModel.find({userId}).populate("shopId").populate("productId");
    return result; 
};

module.exports = {
    addToFavourite,
    getAllFavourites
}