import { config } from "dotenv";
import path from "node:path";
config({ path: path.resolve(process.cwd(), ".env.local") });

async function main() {
  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) throw new Error("DATABASE_URL not set");

  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const schema = await import("./schema");
  const { productPageDefaults } = await import(
    "../product-pages/defaults"
  );

  const sql = postgres(databaseUrl, { max: 1 });
  const db = drizzle(sql, { schema });

  let inserted = 0;
  let updated = 0;

  for (const row of productPageDefaults) {
    const result = await db
      .insert(schema.productPages)
      .values(row)
      .onConflictDoUpdate({
        target: schema.productPages.slug,
        set: { ...row, updatedAt: new Date() },
      })
      .returning({ slug: schema.productPages.slug });
    if (result.length > 0) {
      // onConflictDoUpdate always returns the row; can't tell insert vs update
      // from the return value alone. Count as inserted-or-updated.
      inserted += 1;
    }
  }

  console.log(
    `product_pages seed complete — ${inserted} inserted/updated, ${updated} skipped`,
  );
  await sql.end();
  process.exit(0);
}

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