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

// Seeds atlas_regions (7) + atlas_conditions (~35) from the static TS files.
// Idempotent on slug. Safe to re-run.

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 { regions } = await import("../../data/atlas/regions");
  const { conditions } = await import("../../data/atlas/conditions");

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

  let insertedRegions = 0;
  let updatedRegions = 0;

  for (let i = 0; i < regions.length; i++) {
    const r = regions[i];
    const values = {
      slug: r.slug,
      name: r.name,
      summary: r.summary,
      icon: r.icon ?? null,
      photoUrl: r.photoUrl ?? null,
      photoAlt: r.photoAlt ?? null,
      status: "published" as const,
      position: i,
    };
    const [existing] = await db
      .select({ id: schema.atlasRegions.id })
      .from(schema.atlasRegions)
      .where(eq(schema.atlasRegions.slug, r.slug))
      .limit(1);
    if (existing) {
      await db
        .update(schema.atlasRegions)
        .set({ ...values, updatedAt: new Date() })
        .where(eq(schema.atlasRegions.id, existing.id));
      updatedRegions += 1;
    } else {
      await db.insert(schema.atlasRegions).values(values);
      insertedRegions += 1;
    }
  }

  let insertedConditions = 0;
  let updatedConditions = 0;

  for (let i = 0; i < conditions.length; i++) {
    const c = conditions[i];
    const values = {
      slug: c.slug,
      name: c.name,
      regionSlug: c.regionSlug,
      category: c.category,
      summary: c.summary,
      sections: c.sections,
      referencesList: c.references ?? [],
      status: "published" as const,
      position: i,
    };
    const [existing] = await db
      .select({ id: schema.atlasConditions.id })
      .from(schema.atlasConditions)
      .where(eq(schema.atlasConditions.slug, c.slug))
      .limit(1);
    if (existing) {
      await db
        .update(schema.atlasConditions)
        .set({ ...values, updatedAt: new Date() })
        .where(eq(schema.atlasConditions.id, existing.id));
      updatedConditions += 1;
    } else {
      await db.insert(schema.atlasConditions).values(values);
      insertedConditions += 1;
    }
  }

  console.log(
    `atlas seed complete — regions: ${insertedRegions} inserted / ${updatedRegions} updated, conditions: ${insertedConditions} inserted / ${updatedConditions} updated`,
  );
  await sql.end();
  process.exit(0);
}

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