import { sql } from '@vercel/postgres'; export default async function handler(req, res) { // Set CORS headers res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Handle preflight requests if (req.method === 'OPTIONS') { res.status(200).end(); return; } if (req.method !== 'GET') { return res.status(405).json({ error: 'Method not allowed' }); } try { const { q = '', limit = 20 } = req.query; let result; if (q.trim()) { // Search by name result = await sql` SELECT id, name, set_name, rarity, card_type, image_url, market_price, game FROM cards WHERE name ILIKE ${`%${q}%`} ORDER BY name LIMIT ${parseInt(limit)} `; } else { // Return all cards if no search query result = await sql` SELECT id, name, set_name, rarity, card_type, image_url, market_price, game FROM cards ORDER BY name LIMIT ${parseInt(limit)} `; } res.status(200).json({ success: true, cards: result.rows, pagination: { page: 1, limit: parseInt(limit), total: result.rows.length, pages: 1 }, filters: { games: [...new Set(result.rows.map(card => card.game).filter(Boolean))], rarities: [...new Set(result.rows.map(card => card.rarity).filter(Boolean))], sets: [...new Set(result.rows.map(card => card.set_name).filter(Boolean))] } }); } catch (error) { console.error('Error searching cards:', error); res.status(500).json({ error: 'Internal server error' }); } }