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' });
    }

    const { id } = req.query;
    const cardId = parseInt(id, 10);

    if (!id || Number.isNaN(cardId)) {
      return res.status(400).json({ error: 'Valid card ID is required' });
    }

    if (req.method === 'GET') {
      const result = await sql`
        SELECT COALESCE(SUM(quantity), 0) AS quantity
        FROM user_cards
        WHERE user_id = ${user.userId} AND card_id = ${cardId}
      `;

      return res.status(200).json({
        quantity: parseInt(result.rows[0]?.quantity, 10) || 0,
      });
    }

    if (req.method !== 'POST') {
      return res.status(405).json({ error: 'Method not allowed' });
    }

    const { quantity } = req.body;

    if (quantity === undefined) {
      return res.status(400).json({ error: 'Quantity is required' });
    }

    const cardQuantity = parseInt(quantity, 10);

    if (Number.isNaN(cardQuantity) || cardQuantity < 0) {
      return res.status(400).json({ error: 'Invalid quantity' });
    }

    // Verify the card exists
    const cardCheck = await sql`SELECT id, name FROM cards WHERE id = ${cardId}`;
    if (cardCheck.rows.length === 0) {
      return res.status(404).json({ error: 'Card not found' });
    }

    const card = cardCheck.rows[0];

    // Find the user's "All My Cards" collection
    const allMyCardsCollection = await sql`
      SELECT id FROM collections 
      WHERE user_id = ${user.userId} 
      AND name = 'All My Cards' 
      AND is_system_collection = true
    `;

    if (allMyCardsCollection.rows.length === 0) {
      return res.status(500).json({ error: 'All My Cards collection not found' });
    }

    const collectionId = allMyCardsCollection.rows[0].id;

    if (cardQuantity > 0) {
      // Insert or update user's card ownership
      const result = await sql`
        INSERT INTO user_cards (user_id, card_id, quantity, created_at, updated_at)
        VALUES (${user.userId}, ${cardId}, ${cardQuantity}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ON CONFLICT (user_id, card_id)
        DO UPDATE SET 
          quantity = ${cardQuantity},
          updated_at = CURRENT_TIMESTAMP
        RETURNING *
      `;

      // Sync with "All My Cards" collection
      const collectionCardResult = await sql`
        INSERT INTO collection_cards (collection_id, card_id, quantity, created_at)
        VALUES (${collectionId}, ${cardId}, ${cardQuantity}, CURRENT_TIMESTAMP)
        ON CONFLICT (collection_id, card_id)
        DO UPDATE SET 
          quantity = ${cardQuantity}
        RETURNING *
      `;

      res.status(200).json({
        success: true,
        message: 'Card ownership updated and synced to All My Cards collection',
        card: {
          id: card.id,
          name: card.name,
          quantity: result.rows[0].quantity
        }
      });

    } else {
      // Remove card ownership
      await sql`DELETE FROM user_cards WHERE user_id = ${user.userId} AND card_id = ${cardId}`;
      
      // Remove from "All My Cards" collection
      await sql`DELETE FROM collection_cards WHERE collection_id = ${collectionId} AND card_id = ${cardId}`;

      res.status(200).json({
        success: true,
        message: 'Card ownership removed and synced from All My Cards collection',
        card: {
          id: card.id,
          name: card.name,
          quantity: 0
        }
      });
    }

  } catch (error) {
    console.error('Error handling ownership:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
} 