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

async function main() {
  if (!process.env.DATABASE_URL) 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("../src/lib/db/schema");
  const { EMAIL_TEMPLATE_DEFAULTS } = await import(
    "../src/lib/email/template-defaults"
  );

  const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
  const db = drizzle(sql, { schema });

  let inserted = 0;
  for (const tpl of EMAIL_TEMPLATE_DEFAULTS) {
    const result = await db
      .insert(schema.emailTemplates)
      .values(tpl)
      .onConflictDoNothing({ target: schema.emailTemplates.slug })
      .returning({ slug: schema.emailTemplates.slug });
    if (result.length > 0) inserted += 1;
  }
  console.log(
    `Seeded ${inserted}/${EMAIL_TEMPLATE_DEFAULTS.length} email templates.`,
  );
  await sql.end();
}

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