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 { limit = 6 } = req.query; // Get featured public collections for landing page (no auth required) const result = await sql` SELECT DISTINCT c.*, u.email as creator_email, u.username as creator_username, COUNT(cc.card_id) as card_count, COALESCE(SUM(cards.market_price * cc.quantity), 0) as total_value FROM collections c LEFT JOIN users u ON c.user_id = u.id LEFT JOIN collection_cards cc ON c.id = cc.collection_id LEFT JOIN cards ON cc.card_id = cards.id WHERE c.is_public = true AND (c.is_system_collection IS NULL OR c.is_system_collection = false) GROUP BY c.id, u.email, u.username ORDER BY c.updated_at DESC, c.created_at DESC LIMIT ${parseInt(limit)} `; const collections = result.rows.map(collection => ({ id: collection.id, slug: collection.slug, name: collection.name, description: collection.description, tcg: collection.tcg || 'MTG', cardCount: parseInt(collection.card_count) || 0, value: parseFloat(collection.total_value) || 0, lastViewed: collection.updated_at, createdAt: collection.created_at, isPublic: collection.is_public || false, tags: collection.tags ? collection.tags.split(',') : [], creator: collection.creator_username || collection.creator_email, image: collection.image })); res.status(200).json(collections); } catch (error) { console.error('Error fetching public collections:', error); res.status(500).json({ error: 'Internal server error' }); } }