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

async function getSets(req, res) {
  try {
    const [rows] = await db.execute(`
      SELECT
        s.id, s.set_name, s.set_code, s.num_of_cards, s.tcg_date,
        COUNT(DISTINCT csr.card_id) AS total_in_db,
        COUNT(DISTINCT CASE WHEN csr.amount_owned > 0 THEN csr.card_id END) AS owned_count
      FROM sets s
      LEFT JOIN card_sets_rarity csr ON s.id = csr.set_id
      GROUP BY s.id
      ORDER BY s.tcg_date DESC, s.set_name ASC
    `);
    res.json(rows);
  } catch (err) {
    console.error('Error fetching sets:', err);
    res.status(500).json({ error: 'Failed to fetch sets' });
  }
}

async function getSetCards(req, res) {
  const { setId } = req.params;
  try {
    const [rows] = await db.execute(`
      SELECT
        c.id, c.name, c.card_type AS type, c.frame_type,
        csr.card_set_code AS set_code,
        r.id AS rarity_id, r.rarity_name, r.rarity_code,
        csr.amount_owned
      FROM card_sets_rarity csr
      JOIN cards c ON csr.card_id = c.id
      JOIN rarities r ON csr.rarity_id = r.id
      WHERE csr.set_id = ?
      ORDER BY c.name ASC
    `, [setId]);
    res.json(rows);
  } catch (err) {
    console.error('Error fetching set cards:', err);
    res.status(500).json({ error: 'Failed to fetch set cards' });
  }
}

module.exports = { getSets, getSetCards };
