62 lines
2 KiB
JavaScript
62 lines
2 KiB
JavaScript
|
|
import { sql } from '@vercel/postgres';
|
||
|
|
import { getUserFromRequest } from '../../lib/permission-middleware';
|
||
|
|
|
||
|
|
export default async function handler(req, res) {
|
||
|
|
try {
|
||
|
|
const user = await getUserFromRequest(req);
|
||
|
|
if (!user) {
|
||
|
|
return res.status(401).json({ error: 'Authentication required' });
|
||
|
|
}
|
||
|
|
|
||
|
|
if (req.method === 'POST') {
|
||
|
|
const { cardId, quantity = 1, condition = 'NM', is_foil = false } = req.body;
|
||
|
|
|
||
|
|
if (!cardId) {
|
||
|
|
return res.status(400).json({ error: 'Card ID is required' });
|
||
|
|
}
|
||
|
|
|
||
|
|
// Check if user already owns this card
|
||
|
|
const existingResult = await sql`
|
||
|
|
SELECT * FROM user_cards
|
||
|
|
WHERE user_id = ${user.userId} AND card_id = ${cardId} AND is_foil = ${is_foil}
|
||
|
|
`;
|
||
|
|
|
||
|
|
if (existingResult.rows.length > 0) {
|
||
|
|
// Update quantity
|
||
|
|
const newQuantity = existingResult.rows[0].quantity + quantity;
|
||
|
|
await sql`
|
||
|
|
UPDATE user_cards
|
||
|
|
SET quantity = ${newQuantity}, updated_at = CURRENT_TIMESTAMP
|
||
|
|
WHERE user_id = ${user.userId} AND card_id = ${cardId} AND is_foil = ${is_foil}
|
||
|
|
`;
|
||
|
|
} else {
|
||
|
|
// Insert new record
|
||
|
|
await sql`
|
||
|
|
INSERT INTO user_cards (user_id, card_id, quantity, condition, is_foil)
|
||
|
|
VALUES (${user.userId}, ${cardId}, ${quantity}, ${condition}, ${is_foil})
|
||
|
|
`;
|
||
|
|
}
|
||
|
|
|
||
|
|
return res.status(200).json({ message: 'Card added to owned cards' });
|
||
|
|
|
||
|
|
} else if (req.method === 'GET') {
|
||
|
|
// Get user's owned cards
|
||
|
|
const result = await sql`
|
||
|
|
SELECT uc.*, c.name, c.set_name, c.rarity, c.game, c.image_url
|
||
|
|
FROM user_cards uc
|
||
|
|
JOIN cards c ON uc.card_id = c.id
|
||
|
|
WHERE uc.user_id = ${user.userId}
|
||
|
|
ORDER BY uc.created_at DESC
|
||
|
|
`;
|
||
|
|
|
||
|
|
return res.status(200).json(result.rows);
|
||
|
|
|
||
|
|
} else {
|
||
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
||
|
|
}
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Error in user-cards API:', error);
|
||
|
|
return res.status(500).json({ error: 'Internal server error' });
|
||
|
|
}
|
||
|
|
}
|