/**
 * One-off backfill: create a default household for every user that does not
 * have a household_members row yet. Used after the auto-household onboarding
 * change to avoid leaving existing staging/test users stranded.
 */
import { config as loadDotenv } from "dotenv";
import path from "node:path";
import { existsSync } from "node:fs";

for (const candidate of [".env", "../.env", "../../.env"]) {
  const p = path.resolve(process.cwd(), candidate);
  if (existsSync(p)) {
    loadDotenv({ path: p });
    break;
  }
}

import { createDatabase, closeDatabase, schema } from "@app/database";
import { eq, isNull } from "drizzle-orm";
import { createHouseholdWithDefaults } from "../src/lib/helpers.js";
import { t } from "../src/lib/i18n.js";

async function main() {
  const dbUrl = process.env.DATABASE_URL;
  if (!dbUrl) {
    console.error("Sätt DATABASE_URL innan backfill körs.");
    process.exit(1);
  }

  const { db, pool } = createDatabase(dbUrl);

  const usersWithoutHousehold = await db
    .select({ id: schema.users.id, locale: schema.users.locale })
    .from(schema.users)
    .leftJoin(
      schema.householdMembers,
      eq(schema.householdMembers.userId, schema.users.id),
    )
    .where(isNull(schema.householdMembers.userId));

  console.log(`[backfill] Hittade ${usersWithoutHousehold.length} användare utan hushåll.`);

  let created = 0;
  for (const user of usersWithoutHousehold) {
    const name = t("onboarding.householdDefaultName", user.locale ?? "sv-SE");
    await createHouseholdWithDefaults(db, { userId: user.id, name, size: 1 });
    created++;
  }

  console.log(`[backfill] Skapade ${created} hushåll.`);
  await closeDatabase();
  await pool.end();
}

main().catch((err) => {
  console.error("[backfill] MISSLYCKADES:", err);
  process.exit(1);
});
