/**
 * Seeds ~70 stub games (slug + title only, status='seeded') plus the
 * platforms taxonomy. Run with: npm run seed
 *
 * This mirrors the admin panel's "Bulk import (CSV/JSON)" feature for local
 * setup — the same JSON shape can be pasted into that importer later.
 */
import { createClient } from "@supabase/supabase-js";
import seedGames from "../data/seed-games.json";

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);

const PLATFORM_DEFS: Record<string, string> = {
  pc: "PC",
  android: "Android",
  ios: "iOS",
  ps: "PlayStation",
  xbox: "Xbox",
};

async function main() {
  console.log("Seeding platforms…");
  const platformIds: Record<string, string> = {};
  for (const [slug, name] of Object.entries(PLATFORM_DEFS)) {
    const { data, error } = await supabase
      .from("platforms")
      .upsert({ slug, name }, { onConflict: "slug" })
      .select("id, slug")
      .single();
    if (error) throw error;
    platformIds[slug] = data.id;
  }

  console.log(`Seeding ${seedGames.length} game stubs…`);
  for (const g of seedGames as { title: string; slug: string; platforms: string[] }[]) {
    const { data: game, error } = await supabase
      .from("games")
      .upsert({ title: g.title, slug: g.slug, status: "seeded" }, { onConflict: "slug" })
      .select("id")
      .single();
    if (error) {
      console.error(`  ! ${g.slug}:`, error.message);
      continue;
    }
    const links = g.platforms.map((p) => ({ game_id: game.id, platform_id: platformIds[p] }));
    await supabase.from("game_platforms").upsert(links, { onConflict: "game_id,platform_id" });
    console.log(`  + ${g.slug}`);
  }

  console.log("Done.");
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
