import { sql } from '@vercel/postgres';

/**
 * Import all cards for a Scryfall set code. Skips rows already present by scryfall_id.
 */
export async function importMtgSet(setCode) {
  const response = await fetch(`https://api.scryfall.com/cards/search?q=set:${setCode}`);

  if (!response.ok) {
    throw new Error(`Scryfall API error: ${response.status}`);
  }

  const data = await response.json();
  const cards = data.data || [];

  let imported = 0;
  let skipped = 0;

  for (const card of cards) {
    try {
      const existingCard = await sql`
        SELECT id FROM cards WHERE scryfall_id = ${card.id}
      `;

      if (existingCard.rows.length > 0) {
        skipped += 1;
        continue;
      }

      let currentPrice = null;
      let marketPrice = null;

      if (card.prices) {
        currentPrice = card.prices.usd ? parseFloat(card.prices.usd) : null;
        marketPrice = card.prices.usd_foil ? parseFloat(card.prices.usd_foil) : null;
      }

      await sql`
        INSERT INTO cards (
          name, set_name, set_code, card_number, rarity, game,
          mana_cost, cmc, card_type, colors, oracle_text,
          power, toughness, image_url, stock_image_url,
          current_price, market_price, scryfall_id, verified
        ) VALUES (
          ${card.name}, ${card.set_name}, ${card.set}, ${card.collector_number},
          ${card.rarity}, 'MTG', ${card.mana_cost || null}, ${card.cmc || null},
          ${card.type_line}, ${JSON.stringify(card.colors || [])},
          ${card.oracle_text || null}, ${card.power || null}, ${card.toughness || null},
          ${card.image_uris?.normal || null}, ${card.image_uris?.art_crop || null},
          ${currentPrice}, ${marketPrice}, ${card.id}, true
        )
      `;

      imported += 1;
    } catch (error) {
      console.error(`[importMtgSet] Error importing card ${card.name}:`, error);
      skipped += 1;
    }
  }

  return { setCode, imported, skipped, total: cards.length };
}
