import { sql } from '@vercel/postgres'; export default async function handler(req, res) { const { id } = req.query; if (req.method === 'GET') { try { const result = await sql` SELECT id, name, set_name, set_code, card_number, rarity, game, mana_cost, cmc, card_type, colors, oracle_text, power, toughness, image_url, stock_image_url, current_price, market_price, scryfall_id, verified, created_at, updated_at FROM cards WHERE id = ${id} `; if (result.rows.length === 0) { return res.status(404).json({ error: 'Card not found' }); } const card = result.rows[0]; // Parse JSON fields if (card.colors) { try { card.colors = JSON.parse(card.colors); } catch (e) { card.colors = []; } } res.status(200).json({ success: true, card }); } catch (error) { console.error('Card fetch error:', error); res.status(500).json({ error: 'Failed to fetch card', details: error.message }); } } else if (req.method === 'PUT') { try { const { name, set_name, set_code, card_number, rarity, game, mana_cost, cmc, card_type, colors, oracle_text, power, toughness, image_url, stock_image_url, current_price, market_price } = req.body; const result = await sql` UPDATE cards SET name = ${name}, set_name = ${set_name}, set_code = ${set_code}, card_number = ${card_number}, rarity = ${rarity}, game = ${game}, mana_cost = ${mana_cost}, cmc = ${cmc}, card_type = ${card_type}, colors = ${JSON.stringify(colors)}, oracle_text = ${oracle_text}, power = ${power}, toughness = ${toughness}, image_url = ${image_url}, stock_image_url = ${stock_image_url}, current_price = ${current_price}, market_price = ${market_price}, updated_at = CURRENT_TIMESTAMP WHERE id = ${id} RETURNING * `; if (result.rows.length === 0) { return res.status(404).json({ error: 'Card not found' }); } res.status(200).json({ success: true, card: result.rows[0] }); } catch (error) { console.error('Card update error:', error); res.status(500).json({ error: 'Failed to update card', details: error.message }); } } else if (req.method === 'DELETE') { try { const result = await sql` DELETE FROM cards WHERE id = ${id} `; res.status(200).json({ success: true, message: 'Card deleted successfully' }); } catch (error) { console.error('Card delete error:', error); res.status(500).json({ error: 'Failed to delete card', details: error.message }); } } else { res.status(405).json({ error: 'Method not allowed' }); } }