/**
 * One-off password update for a single login.
 *
 *   dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/set-user-password.ts \
 *     --email admin@rms.local --password 'new-secret'
 *
 * Refuses to invent a password — the caller must pass one, so nothing random
 * ends up in a log with no copy left for the operator.
 */
import { PrismaClient } from '@prisma/client';
import { hashPassword } from '../src/auth/password';

function arg(name: string): string | undefined {
  const i = process.argv.indexOf(`--${name}`);
  return i >= 0 ? process.argv[i + 1] : undefined;
}

async function main() {
  const email = arg('email')?.trim().toLowerCase();
  const password = arg('password');
  if (!email || !password) {
    throw new Error('Usage: set-user-password.ts --email <email> --password <password>');
  }
  if (password.length < 8) {
    throw new Error('Password must be at least 8 characters');
  }

  const prisma = new PrismaClient();
  try {
    const user = await prisma.user.findUnique({ where: { email } });
    if (!user || user.deletedAt) {
      throw new Error(`No active user with email ${email}`);
    }
    await prisma.user.update({
      where: { id: user.id },
      data: { passwordHash: hashPassword(password), mustChangePassword: false },
    });
    console.log(`Password updated for ${email}`);
  } finally {
    await prisma.$disconnect();
  }
}

main().catch((err) => {
  console.error(err instanceof Error ? err.message : err);
  process.exit(1);
});
