import { sql } from '@vercel/postgres'; import { getUserFromRequest } from '../../../../lib/permission-middleware'; export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } const { id } = req.query; const { favorited } = req.body; try { // Get authenticated user const user = await getUserFromRequest(req); if (!user) { return res.status(401).json({ error: 'Authentication required' }); } // Check if card exists const cardCheck = await sql` SELECT id, name FROM cards WHERE id = ${id} `; if (cardCheck.rows.length === 0) { return res.status(404).json({ error: 'Card not found' }); } const card = cardCheck.rows[0]; if (favorited) { // Add to user favorites await sql` INSERT INTO user_favorites (user_id, item_type, item_id) VALUES (${user.userId}, 'card', ${id}) ON CONFLICT (user_id, item_type, item_id) DO NOTHING `; } else { // Remove from user favorites await sql` DELETE FROM user_favorites WHERE user_id = ${user.userId} AND item_type = 'card' AND item_id = ${id} `; } res.status(200).json({ success: true, card: { id: card.id, name: card.name, favorited: favorited } }); } catch (error) { console.error('Error updating favorite status:', error); res.status(500).json({ error: 'Failed to update favorite status' }); } }