/**
 * Set the admin credentials for the production deployment:
 * rename/disable any existing admin and create/update user `inkreach`.
 *
 * Usage (inside the api container):  node scripts/set-admin.mjs
 * Reads NEW_ADMIN_USER / NEW_ADMIN_PASSWORD from env.
 */
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcrypt';

const prisma = new PrismaClient();

async function main() {
  const username = process.env.NEW_ADMIN_USER;
  const password = process.env.NEW_ADMIN_PASSWORD;
  if (!username || !password) {
    console.error('NEW_ADMIN_USER / NEW_ADMIN_PASSWORD must be set');
    process.exit(1);
  }

  const passwordHash = await bcrypt.hash(password, 10);
  await prisma.user.upsert({
    where: { username },
    create: { username, passwordHash },
    update: { passwordHash, tokenVersion: { increment: 1 } },
  });

  // Remove every other admin so only `inkreach` can sign in.
  const others = await prisma.user.deleteMany({
    where: { username: { not: username } },
  });

  const total = await prisma.user.count();
  console.log(`Admin '${username}' set. Demoted ${others.count} other user(s). Total users: ${total}.`);
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
