2026-08-15 10:32:13 -04:00
|
|
|
import { sql } from '../../../../lib/sql.js';
|
2025-07-26 01:29:51 -04:00
|
|
|
import { getUserFromRequest } from '../../../../lib/permission-middleware';
|
2025-07-24 16:03:09 -04:00
|
|
|
|
|
|
|
|
export default async function handler(req, res) {
|
|
|
|
|
const { id } = req.query;
|
|
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
|
|
|
|
try {
|
2025-07-26 01:29:51 -04:00
|
|
|
// Get authenticated user
|
|
|
|
|
const user = await getUserFromRequest(req);
|
|
|
|
|
if (!user) {
|
|
|
|
|
return res.status(401).json({ error: 'Authentication required' });
|
|
|
|
|
}
|
2025-07-24 16:03:09 -04:00
|
|
|
|
2025-07-26 01:29:51 -04:00
|
|
|
// Get decks that contain this card and belong to the user
|
|
|
|
|
const result = await sql`
|
|
|
|
|
SELECT DISTINCT
|
|
|
|
|
d.id,
|
|
|
|
|
d.name,
|
|
|
|
|
d.description,
|
|
|
|
|
dc.quantity
|
|
|
|
|
FROM decks d
|
|
|
|
|
JOIN deck_cards dc ON d.id = dc.deck_id
|
|
|
|
|
WHERE dc.card_id = ${id}
|
|
|
|
|
AND d.user_id = ${user.userId}
|
|
|
|
|
ORDER BY d.name
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
res.status(200).json(result.rows);
|
2025-07-24 16:03:09 -04:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error fetching card decks:', error);
|
|
|
|
|
res.status(500).json({ error: 'Failed to fetch card decks' });
|
|
|
|
|
}
|
|
|
|
|
} else if (req.method === 'POST') {
|
|
|
|
|
try {
|
2025-07-26 01:29:51 -04:00
|
|
|
// Get authenticated user
|
|
|
|
|
const user = await getUserFromRequest(req);
|
|
|
|
|
if (!user) {
|
|
|
|
|
return res.status(401).json({ error: 'Authentication required' });
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-24 16:03:09 -04:00
|
|
|
const { deckId } = req.body;
|
|
|
|
|
|
2025-07-26 01:29:51 -04:00
|
|
|
// Check if user owns this deck
|
|
|
|
|
const deckCheck = await sql`
|
|
|
|
|
SELECT id, name
|
|
|
|
|
FROM decks
|
|
|
|
|
WHERE id = ${deckId} AND user_id = ${user.userId}
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
if (deckCheck.rows.length === 0) {
|
|
|
|
|
return res.status(403).json({ error: 'Deck not found or access denied' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add card to deck
|
|
|
|
|
await sql`
|
|
|
|
|
INSERT INTO deck_cards (deck_id, card_id, quantity)
|
|
|
|
|
VALUES (${deckId}, ${id}, 1)
|
|
|
|
|
ON CONFLICT (deck_id, card_id)
|
|
|
|
|
DO UPDATE SET quantity = deck_cards.quantity + 1
|
|
|
|
|
`;
|
|
|
|
|
|
2025-07-24 16:03:09 -04:00
|
|
|
res.status(200).json({
|
|
|
|
|
success: true,
|
|
|
|
|
message: 'Card added to deck'
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error adding card to deck:', error);
|
|
|
|
|
res.status(500).json({ error: 'Failed to add card to deck' });
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
res.status(405).json({ error: 'Method not allowed' });
|
|
|
|
|
}
|
|
|
|
|
}
|