import 'dotenv/config';
import 'temporal-polyfill/full/global';
import * as bcrypt from 'bcrypt';
import { loadAppConfig } from '../config/app.config.js';
import { normalizeEmail, normalizeRequiredString } from '../common/utils/normalize.js';
import { db } from '../prisma/db.js';

type BootstrapArgs = {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
};

function printUsage(): void {
  console.log(`Usage:
  npm run bootstrap:admin -- --email=admin@example.com --password=... --firstName=Admin --lastName=User

Creates the first ADMIN user in PostgreSQL.
Fails if any ADMIN user already exists.
Password is never logged.
`);
}

function parseArgs(argv: string[]): BootstrapArgs {
  const values: Record<string, string> = {};

  for (const arg of argv) {
    if (!arg.startsWith('--')) {
      continue;
    }

    const [key, ...rest] = arg.slice(2).split('=');
    if (!key || rest.length === 0) {
      continue;
    }
    values[key] = rest.join('=');
  }

  const firstName = values['firstName'];
  const lastName = values['lastName'];
  const email = values['email'];
  const password = values['password'];

  if (!firstName || !lastName || !email || !password) {
    throw new Error(
      'Missing required args: --email --password --firstName --lastName',
    );
  }

  if (password.length < 8) {
    throw new Error('Password must be at least 8 characters');
  }

  return { firstName, lastName, email, password };
}

async function main(): Promise<void> {
  const args = parseArgs(process.argv.slice(2));
  const config = loadAppConfig();

  const email = normalizeEmail(args.email);
  const firstName = normalizeRequiredString(args.firstName);
  const lastName = normalizeRequiredString(args.lastName);

  const existingAdmin = await db.orm.public.User.where((u) =>
    u.role.eq('ADMIN'),
  ).first();

  if (existingAdmin) {
    throw new Error(
      'An ADMIN user already exists. Bootstrap aborted (no changes made).',
    );
  }

  const existingEmail = await db.orm.public.User.where((u) =>
    u.email.eq(email),
  ).first();

  if (existingEmail) {
    throw new Error(
      'A user with this email already exists. Bootstrap aborted.',
    );
  }

  const passwordHash = await bcrypt.hash(args.password, config.bcryptRounds);

  const admin = await db.orm.public.User.select(
    'id',
    'email',
    'role',
    'isActive',
    'createdAt',
  ).create({
    firstName,
    lastName,
    email,
    passwordHash,
    role: 'ADMIN',
    isActive: true,
  });

  console.log('Initial ADMIN created successfully.');
  console.log(`id=${admin.id}`);
  console.log(`email=${admin.email}`);
  console.log(`role=${admin.role}`);
  console.log(`isActive=${admin.isActive}`);
}

main()
  .catch((error: unknown) => {
    const message =
      error instanceof Error ? error.message : 'Bootstrap failed';
    console.error(message);
    process.exitCode = 1;
  })
  .finally(async () => {
    await db.close();
  });
