2025-07-24 16:03:09 -04:00
|
|
|
import { sql } from '@vercel/postgres';
|
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) {
|
|
|
|
|
if (req.method !== 'POST') {
|
|
|
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { id } = req.query;
|
|
|
|
|
const { quantity } = req.body;
|
|
|
|
|
|
|
|
|
|
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' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if card exists
|
|
|
|
|
const cardCheck = await sql`
|
|
|
|
|
SELECT id, name FROM cards WHERE id = ${id}
|
2025-07-24 16:03:09 -04:00
|
|
|
`;
|
|
|
|
|
|
2025-07-26 01:29:51 -04:00
|
|
|
if (cardCheck.rows.length === 0) {
|
2025-07-24 16:03:09 -04:00
|
|
|
return res.status(404).json({ error: 'Card not found' });
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-26 01:29:51 -04:00
|
|
|
const card = cardCheck.rows[0];
|
|
|
|
|
|
|
|
|
|
if (quantity > 0) {
|
|
|
|
|
// Insert or update user's card ownership
|
|
|
|
|
const result = await sql`
|
|
|
|
|
INSERT INTO user_cards (user_id, card_id, quantity)
|
|
|
|
|
VALUES (${user.userId}, ${id}, ${quantity})
|
|
|
|
|
ON CONFLICT (user_id, card_id)
|
|
|
|
|
DO UPDATE SET
|
|
|
|
|
quantity = ${quantity},
|
|
|
|
|
updated_at = CURRENT_TIMESTAMP
|
|
|
|
|
RETURNING *
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
res.status(200).json({
|
|
|
|
|
success: true,
|
|
|
|
|
card: {
|
|
|
|
|
id: card.id,
|
|
|
|
|
name: card.name,
|
|
|
|
|
quantity: result.rows[0].quantity
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
// Remove card from user's collection if quantity is 0
|
|
|
|
|
await sql`
|
|
|
|
|
DELETE FROM user_cards
|
|
|
|
|
WHERE user_id = ${user.userId} AND card_id = ${id}
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
res.status(200).json({
|
|
|
|
|
success: true,
|
|
|
|
|
card: {
|
|
|
|
|
id: card.id,
|
|
|
|
|
name: card.name,
|
|
|
|
|
quantity: 0
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-07-24 16:03:09 -04:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error updating ownership:', error);
|
|
|
|
|
res.status(500).json({ error: 'Failed to update ownership' });
|
|
|
|
|
}
|
|
|
|
|
}
|