/**
 * create-admin — local-dev helper to create the first admin user.
 *
 * Fresh installs ship with ZERO users by design (see prisma/seed.ts): in
 * production the operator creates the first admin via the StartOS Action
 * "Set admin credentials". Local dev has no StartOS, so this script is the
 * equivalent — it creates an admin and seeds their curated library, exactly
 * like the StartOS action does.
 *
 * Usage (from proof-of-work/):
 *   npm run create-admin -- <email> <password> [name]
 *   ADMIN_EMAIL=me@example.com ADMIN_PASSWORD=secret123 npm run create-admin
 *
 * The email must be a real-looking address (login/signup validate the TLD);
 * "admin@local" will NOT work.
 */
import { prisma } from "../lib/prisma";
import { hashPassword } from "../lib/auth";
import { ensureLibraryForUser } from "../lib/library";

async function main() {
  const force = process.argv.includes("--force");
  const positional = process.argv.slice(2).filter((a) => !a.startsWith("--"));
  const email = positional[0] || process.env.ADMIN_EMAIL;
  const password = positional[1] || process.env.ADMIN_PASSWORD;
  const name = positional[2] || process.env.ADMIN_NAME || null;

  if (!email || !password) {
    console.error(
      "usage: npm run create-admin -- <email> <password> [name]\n" +
        "   or: ADMIN_EMAIL=... ADMIN_PASSWORD=... npm run create-admin",
    );
    process.exit(64);
  }
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
    console.error(
      `Refusing "${email}": login/signup require a real email with a TLD ` +
        '(e.g. you@example.com). "admin@local" will not work.',
    );
    process.exit(64);
  }
  if (password.length < 8) {
    console.error("Password must be at least 8 characters.");
    process.exit(64);
  }

  // Guard the footgun: a typo'd or reused email would otherwise silently
  // reset an existing user's password AND promote them to admin. Require
  // --force to touch an account that already exists.
  const existing = await prisma.user.findUnique({ where: { email } });
  if (existing && !force) {
    console.error(
      `A user with ${email} already exists (isAdmin=${existing.isAdmin}). ` +
        "Re-run with --force to RESET its password and promote it to admin.",
    );
    process.exit(73);
  }

  const passwordHash = await hashPassword(password);

  // Upsert so --force re-running promotes/repairs an existing account rather
  // than erroring on the unique-email constraint.
  const user = await prisma.user.upsert({
    where: { email },
    update: { passwordHash, isAdmin: true },
    create: {
      email,
      passwordHash,
      name: name?.trim() || null,
      isAdmin: true,
      userPreferences: {
        create: {
          theme: "system",
          defaultWeightUnit: "lbs",
          defaultRestSeconds: 90,
        },
      },
    },
  });

  const added = await ensureLibraryForUser(user.id);
  console.log(
    `Admin ready: ${email} (id ${user.id}); seeded ${added} library exercises.`,
  );
}

main()
  .catch((e) => {
    console.error("create-admin failed:", e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
