import { prisma } from "../db/prisma.js";
import { syncRecipeSources } from "../db/recipe-source-sync.js";
import { seedReferenceData } from "../db/reference-seed-data.js";
import { registerAllRecipeSources } from "../sources/index.js";

/**
 * Runtime seed entry point for the production Docker image — run via
 * `node dist/scripts/seed-runtime.js` in apps/api/Dockerfile's CMD, after
 * `prisma migrate deploy` and before starting the server.
 *
 * Deliberately separate from `prisma/seed.ts` (the dev-time entry point
 * wired to `prisma db seed`/`prisma migrate reset`): that one imports
 * `seedReferenceData` from `../src/db/...` and runs via `tsx`, but the
 * runtime image only ships compiled `dist` output, not `src` (see the
 * Dockerfile) — this lives under `src/` instead, so `tsc` compiles it
 * alongside everything else, and it runs under plain `node`, no tsx
 * needed at runtime.
 *
 * Also registers and syncs the recipe-source registry
 * (`registerAllRecipeSources`/`syncRecipeSources`) — mirroring
 * `prisma/seed.ts`'s own two calls. Without this, `server.ts`'s own
 * `registerAllRecipeSources()` call only populates *that* process' in-memory
 * registry (each `node` invocation in the Docker CMD chain is a separate
 * process), so the `Source` table itself would stay permanently empty in
 * production and `GET /reference/sources` would always return `[]` — which
 * is exactly what silently hid the whole "sources" section of
 * `HouseholdSettingsPage` (`apps/web`) until this was added.
 *
 * Safe to run on every container start: `seedReferenceData` upserts by
 * each row's unique name, and `syncRecipeSources` is equally idempotent
 * (see its own doc comment) — re-running both against a database that
 * already has this data is a no-op.
 */
registerAllRecipeSources();

seedReferenceData(prisma)
  .then(() => syncRecipeSources(prisma))
  .then(() => prisma.$disconnect())
  .catch(async (err) => {
    console.error(err);
    await prisma.$disconnect();
    process.exit(1);
  });
