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

import {
  fetchPokemonSetCards,
  fetchPokemonSets,
  mapGithubCardForInsert,
} from './pokemon-github.js';

export { fetchWithRetry, fetchPokemonSets } from './pokemon-github.js';

/**
 * Import all cards for a Pokémon set id from the pokemon-tcg-data GitHub repo.
 * Skips rows already present by scryfall_id (legacy column name stores external card ids).
 */
export async function importPokemonSet(setCode) {
  const [sets, cards] = await Promise.all([
    fetchPokemonSets(),
    fetchPokemonSetCards(setCode),
  ]);

  const setMeta = sets.find((set) => set.id?.toLowerCase() === setCode.toLowerCase()) || {
    id: setCode,
    name: setCode,
  };

  if (cards.length === 0) {
    return { setCode, imported: 0, skipped: 0, total: 0 };
  }

  let imported = 0;
  let skipped = 0;

  for (const card of cards) {
    try {
      const mapped = mapGithubCardForInsert(card, setMeta);

      const existingCard = await sql`
        SELECT id FROM cards WHERE scryfall_id = ${mapped.externalId}
      `;

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

      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 (
          ${mapped.name}, ${mapped.setName}, ${mapped.setCode}, ${mapped.cardNumber},
          ${mapped.rarity}, 'Pokemon', null, null, ${mapped.cardType},
          ${JSON.stringify(mapped.types)}, ${mapped.flavorText},
          ${mapped.hp}, null,
          ${mapped.imageSmall}, ${mapped.imageLarge},
          null, null, ${mapped.externalId}, true
        )
      `;

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

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