const db = require('../config/db');

async function exportCards(req, res) {
  const { search, type } = req.query;

  try {
    const conditions = [];
    const cardParams = [];

    if (search?.trim()) {
      conditions.push('LOWER(name) LIKE ?');
      cardParams.push(`%${search.trim().toLowerCase()}%`);
    }
    if (type?.trim()) {
      conditions.push('LOWER(card_type) LIKE ?');
      cardParams.push(`%${type.trim().toLowerCase()}%`);
    }

    const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';

    const [cards] = await db.execute(
      `SELECT id, name, card_type AS type, frame_type, level, race, attribute, link_val, tcg_date, ocg_date
       FROM cards ${where}`,
      cardParams
    );

    if (cards.length === 0) return res.json([]);

    // Only fetch printings for the cards we actually returned
    const cardIds = cards.map(c => c.id);
    const placeholders = cardIds.map(() => '?').join(', ');

    const [printings] = await db.execute(
      `SELECT csr.card_id, csr.set_id, csr.card_set_code AS set_code, csr.amount_owned,
              s.set_name,
              r.id AS rarity_id, r.rarity_name, r.rarity_code
       FROM card_sets_rarity csr
       JOIN sets s ON csr.set_id = s.id
       JOIN rarities r ON csr.rarity_id = r.id
       WHERE csr.card_id IN (${placeholders})`,
      cardIds
    );

    const cardMap = {};
    cards.forEach(card => { cardMap[card.id] = { ...card, printings: [] }; });
    printings.forEach(p => {
      if (cardMap[p.card_id]) {
        cardMap[p.card_id].printings.push({
          set_id: p.set_id,
          set_name: p.set_name,
          set_code: p.set_code,
          rarity_id: p.rarity_id,
          rarity_name: p.rarity_name,
          rarity_code: p.rarity_code,
          amount_owned: p.amount_owned ?? 0,
        });
      }
    });

    res.json(Object.values(cardMap));
  } catch (err) {
    console.error('Error exporting cards:', err);
    res.status(500).json({ error: 'Failed to export cards' });
  }
}

module.exports = { exportCards };
