import "reflect-metadata";
import { config } from "dotenv";
import * as bcrypt from "bcrypt";
import { AppDataSource } from "../data-source";
import { AdminUser } from "../auth/entities/admin-user.entity";

config();

// One-time bootstrap for the first admin account, sourced from env vars so
// no plaintext credential ever lands in a source file. Re-running it is
// safe — it updates the existing seed account instead of duplicating it.
async function main() {
  const email = process.env.ADMIN_SEED_EMAIL;
  const password = process.env.ADMIN_SEED_PASSWORD;
  const name = process.env.ADMIN_SEED_NAME ?? "Admin";

  if (!email || !password) {
    throw new Error("ADMIN_SEED_EMAIL and ADMIN_SEED_PASSWORD must be set (see .env.example).");
  }
  if (password.length < 8) {
    throw new Error("ADMIN_SEED_PASSWORD must be at least 8 characters.");
  }

  const dataSource = await AppDataSource.initialize();
  const repo = dataSource.getRepository(AdminUser);

  const passwordHash = await bcrypt.hash(password, 12);
  const existing = await repo.findOne({ where: { email } });

  if (existing) {
    existing.passwordHash = passwordHash;
    existing.name = name;
    existing.active = true;
    await repo.save(existing);
    console.log(`Updated existing admin account: ${email}`);
  } else {
    await repo.save(repo.create({ email, name, passwordHash, active: true }));
    console.log(`Created admin account: ${email}`);
  }

  await dataSource.destroy();
}

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