import { createClient } from "@supabase/supabase-js";
import { env } from "@/lib/env";

const countries = [
  ["AT", "Austria"],
  ["BE", "Belgium"],
  ["CH", "Switzerland"],
  ["DE", "Germany"],
  ["ES", "Spain"],
  ["FR", "France"],
  ["GB", "United Kingdom"],
  ["IE", "Ireland"],
  ["IT", "Italy"],
  ["NL", "Netherlands"],
  ["PL", "Poland"],
  ["PT", "Portugal"],
  ["SE", "Sweden"],
  ["US", "United States"],
] as const;

async function run() {
  const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

  if (!serviceRoleKey) {
    throw new Error("SUPABASE_SERVICE_ROLE_KEY is required for bootstrap script.");
  }

  const client = createClient(env.supabaseUrl, serviceRoleKey, {
    auth: { autoRefreshToken: false, persistSession: false },
  });

  const countryRows = countries.map(([code, name]) => ({ code, name }));
  const { error: countriesError } = await client
    .from("countries")
    .upsert(countryRows, { onConflict: "code" });
  if (countriesError) throw new Error(countriesError.message);

  const adminEmails = (process.env.ADMIN_EMAILS ?? "")
    .split(",")
    .map((item) => item.trim().toLowerCase())
    .filter(Boolean);

  for (const email of adminEmails) {
    const { error } = await client
      .from("profiles")
      .update({ role: "admin" })
      .ilike("email", email);
    if (error) throw new Error(`Failed to promote ${email}: ${error.message}`);
  }

  console.log(`Seeded ${countries.length} countries.`);
  if (adminEmails.length > 0) {
    console.log(`Promoted admins: ${adminEmails.join(", ")}`);
  }
}

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