<?php
declare(strict_types=1);

// Creates the first administrator. Usage:
//   php bin/create_admin.php "מוטי" moti@example.co.il 'StrongPassphrase'
$api = __DIR__ . '/../api';
require $api . '/lib/Config.php';
require $api . '/lib/DB.php';
Config::load($api . '/config/config.php');

[$script, $name, $email, $pass] = $argv + [null, null, null, null];
if (!$name || !$email || !$pass) {
    fwrite(STDERR, "Usage: php bin/create_admin.php \"Full Name\" email@example.com 'password'\n");
    exit(1);
}
if (strlen($pass) < 10) {
    fwrite(STDERR, "Password must be at least 10 characters.\n");
    exit(1);
}

$roleId = DB::value('SELECT id FROM roles WHERE code = "admin"');
if (!$roleId) {
    fwrite(STDERR, "Roles table is empty. Import database/schema.sql first.\n");
    exit(1);
}
if (DB::value('SELECT id FROM users WHERE email = ?', [strtolower($email)])) {
    fwrite(STDERR, "That email already exists.\n");
    exit(1);
}

$id = DB::insert(
    'INSERT INTO users (role_id, full_name, email, password_hash, twofa_enabled) VALUES (?,?,?,?,0)',
    [$roleId, $name, strtolower($email), password_hash($pass, PASSWORD_BCRYPT)]
);
echo "Administrator created (id {$id}). Sign in, then enable two-factor from the profile page.\n";
