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 === 'GET') {
      // Get user's decks
      const result = await sql`
        SELECT d.*, 
               COUNT(dc.card_id) as card_count,
               SUM(dc.quantity) as total_cards
        FROM decks d
        LEFT JOIN deck_cards dc ON d.id = dc.deck_id
        WHERE d.user_id = ${user.userId}
        GROUP BY d.id
        ORDER BY d.created_at DESC
      `;

      return res.status(200).json(result.rows);

    } else if (req.method === 'POST') {
      const { name, description, game, is_public = false } = req.body;

      if (!name) {
        return res.status(400).json({ error: 'Deck name is required' });
      }

      const result = await sql`
        INSERT INTO decks (user_id, name, description, game, is_public)
        VALUES (${user.userId}, ${name}, ${description || ''}, ${game || 'UNKNOWN'}, ${is_public})
        RETURNING *
      `;

      return res.status(201).json(result.rows[0]);

    } else {
      return res.status(405).json({ error: 'Method not allowed' });
    }

  } catch (error) {
    console.error('Error in decks API:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
} 