// prisma/seed.ts
//
// Run with: npm run seed
// Creates (or updates) the initial admin user for dashboard login. This is
// the MANUAL setup path — if you used the /install wizard instead, this
// already happened for you and you don't need to run this.
//
// Reads credentials from env vars so no plaintext password ever lives in
// source control. Falls back to a generated random password if none is
// provided, which it prints ONCE to the console.

import { PrismaClient } from "@prisma/client";
import { hashPassword, generateSecureToken } from "../lib/crypto";
import { updateEnvFile } from "../lib/env-file";

const prisma = new PrismaClient();

async function main() {
  const username = process.env.SEED_ADMIN_USERNAME || "admin";
  let password = process.env.SEED_ADMIN_PASSWORD;

  let generated = false;
  if (!password) {
    password = generateSecureToken(9); // 18-char hex string
    generated = true;
  }

  const passwordHash = await hashPassword(password);

  const user = await prisma.user.upsert({
    where: { username },
    update: { passwordHash },
    create: { username, passwordHash },
  });

  // Mirrors what the /install wizard does at the end of a successful run —
  // this is the flag middleware.ts checks to decide whether the app is
  // configured yet. Without this, the manual path would still get bounced
  // to /install on every request even after a successful seed.
  updateEnvFile({ INSTALL_COMPLETE: "true" });

  console.log("----------------------------------------------------");
  console.log(`Admin user ready: ${user.username}`);
  if (generated) {
    console.log(`Generated password (SAVE THIS NOW): ${password}`);
    console.log("Set SEED_ADMIN_PASSWORD env var to control this instead.");
  } else {
    console.log("Password set from SEED_ADMIN_PASSWORD env var.");
  }
  console.log("INSTALL_COMPLETE flag set in .env — restart the app process");
  console.log("(e.g. `pm2 restart ecosystem.config.js`) to apply it.");
  console.log("----------------------------------------------------");
}

main()
  .catch((err) => {
    console.error("Seed failed:", err);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
