const Favorite = require('../models/favoriteModel'); const Product = require('../models/productModel'); exports.addToFavorites = async (req, res) => { try { const { productId } = req.body; // Check product exists const productExists = await Product.findById(productId); if (!productExists) { return res.status(404).json({ message: 'Product not found' }); } // Check if user has favorite list let fav = await Favorite.findOne({ user: req.user._id }); if (!fav) { fav = await Favorite.create({ user: req.user._id, products: [productId], }); } else { if (fav.products.some((p) => p.toString() === productId.toString())) { return res .status(400) .json({ message: 'Product already in favorites' }); } fav.products.push(productId); await fav.save(); } res.status(200).json({ status: 'success', favorites: fav, }); } catch (err) { res.status(500).json({ message: 'Failed to add', error: err.message }); } }; exports.removeFromFavorites = async (req, res) => { try { const { productId } = req.body; const fav = await Favorite.findOne({ user: req.user._id }); if (!fav) { return res.status(404).json({ message: 'Favorites list not found' }); } fav.products = fav.products.filter( (p) => p.toString() !== productId.toString(), ); await fav.save(); res.status(200).json({ status: 'success', message: 'Product removed', favorites: fav, }); } catch (err) { res.status(500).json({ message: 'Failed to remove', error: err.message }); } }; exports.getFavorites = async (req, res) => { try { const fav = await Favorite.findOne({ user: req.user._id }).populate( 'products', ); res.status(200).json({ status: 'success', favorites: fav || { user: req.user._id, products: [] }, }); } catch (err) { res .status(500) .json({ message: 'Failed to load favorites', error: err.message }); } }; exports.clearFavorites = async (req, res) => { try { const fav = await Favorite.findOne({ user: req.user._id }); if (!fav) { return res.status(404).json({ message: 'Favorites list not found' }); } fav.products = []; await fav.save(); res.status(200).json({ status: 'success', message: 'All products removed from favorites', favorites: fav, }); } catch (err) { res .status(500) .json({ message: 'Failed to clear favorites', error: err.message }); } };