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

// Seeds the 15 ConsentIQ seed procedures from the TS data file into
// consentiq_procedures. Idempotent on slug.

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 { eq } = await import("drizzle-orm");
  const schema = await import("./schema");
  const { procedures } = await import("../../data/consentiq/procedures");

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

  let inserted = 0;
  let updated = 0;

  for (const p of procedures) {
    const values = {
      slug: p.slug,
      name: p.name,
      region: p.region,
      approxDurationMin: p.approxDurationMin,
      anaesthesia: p.anaesthesia,
      summary: p.summary,
      involves: p.involves,
      options: p.options,
      risks: p.risks.map((r) => ({
        title: r.title,
        detail: r.detail,
        severity: (r.severity ?? "") as "common" | "rare" | "serious" | "",
      })),
      benefits: p.benefits,
      alternatives: p.alternatives,
      recovery: p.recovery,
      warnings: p.warnings,
      status: "published" as const,
    };

    const [existing] = await db
      .select({ id: schema.consentiqProcedures.id })
      .from(schema.consentiqProcedures)
      .where(eq(schema.consentiqProcedures.slug, p.slug))
      .limit(1);

    if (existing) {
      await db
        .update(schema.consentiqProcedures)
        .set({ ...values, updatedAt: new Date() })
        .where(eq(schema.consentiqProcedures.id, existing.id));
      updated += 1;
    } else {
      await db.insert(schema.consentiqProcedures).values(values);
      inserted += 1;
    }
  }

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

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