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 === 'POST') {
      const {
        cardId,
        quantity = 1,
        condition = 'NM',
        is_foil = false,
        scan_image_url: scanImageUrlRaw,
      } = req.body;

      if (!cardId) {
        return res.status(400).json({ error: 'Card ID is required' });
      }

      const parsedQuantity = parseInt(quantity, 10);
      if (Number.isNaN(parsedQuantity) || parsedQuantity < 1) {
        return res.status(400).json({ error: 'Quantity must be at least 1' });
      }

      const scanImageUrl =
        typeof scanImageUrlRaw === 'string' && scanImageUrlRaw.trim().length > 0
          ? scanImageUrlRaw.trim()
          : null;

      // Check if user already owns this card
      const existingResult = await sql`
        SELECT * FROM user_cards 
        WHERE user_id = ${user.userId} AND card_id = ${cardId} AND is_foil = ${is_foil}
      `;

      if (existingResult.rows.length > 0) {
        // Update quantity; preserve existing scan image unless a new URL is supplied
        const newQuantity = existingResult.rows[0].quantity + parsedQuantity;
        await sql`
          UPDATE user_cards 
          SET quantity = ${newQuantity},
              updated_at = CURRENT_TIMESTAMP,
              scan_image_url = COALESCE(${scanImageUrl}, scan_image_url)
          WHERE user_id = ${user.userId} AND card_id = ${cardId} AND is_foil = ${is_foil}
        `;
      } else {
        // Insert new record
        await sql`
          INSERT INTO user_cards (user_id, card_id, quantity, condition, is_foil, scan_image_url)
          VALUES (${user.userId}, ${cardId}, ${parsedQuantity}, ${condition}, ${is_foil}, ${scanImageUrl})
        `;
      }

      return res.status(200).json({ message: 'Card added to owned cards' });

    } else if (req.method === 'GET') {
      // Get user's owned cards
      const result = await sql`
        SELECT uc.*, c.name, c.set_name, c.rarity, c.game, c.image_url
        FROM user_cards uc
        JOIN cards c ON uc.card_id = c.id
        WHERE uc.user_id = ${user.userId}
        ORDER BY uc.created_at DESC
      `;

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

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

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