#!/usr/bin/env php
<?php

use support\Db;

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../support/bootstrap.php';
require __DIR__ . '/../vendor/webman/database/src/support/Db.php';

$username = null;
$password = null;
$displayName = null;

foreach (array_slice($argv, 1) as $argument) {
    if (str_starts_with($argument, '--username=')) {
        $username = substr($argument, strlen('--username='));
        continue;
    }

    if (str_starts_with($argument, '--password=')) {
        $password = substr($argument, strlen('--password='));
        continue;
    }

    if (str_starts_with($argument, '--display_name=')) {
        $displayName = substr($argument, strlen('--display_name='));
    }
}

if (!is_string($username) || trim($username) === '' || !is_string($password) || $password === '') {
    fwrite(STDERR, "Usage: php scripts/setup_admin_users.php --username=<username> --password=<password> [--display_name=<name>]" . PHP_EOL);
    exit(1);
}

$username = trim($username);
$displayName = is_string($displayName) && trim($displayName) !== '' ? trim($displayName) : $username;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);

$statements = [
    <<<SQL
CREATE TABLE IF NOT EXISTS admin_users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(120) NOT NULL UNIQUE,
    display_name TEXT,
    password_hash TEXT NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    last_login_at TIMESTAMPTZ,
    created_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
)
SQL,
    'CREATE INDEX IF NOT EXISTS admin_users_is_active_index ON admin_users (is_active)',
    <<<SQL
CREATE OR REPLACE FUNCTION set_updated_time()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_time = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql
SQL,
    'DROP TRIGGER IF EXISTS admin_users_set_updated_time ON admin_users',
    <<<SQL
CREATE TRIGGER admin_users_set_updated_time
BEFORE UPDATE ON admin_users
FOR EACH ROW
EXECUTE FUNCTION set_updated_time()
SQL,
];

try {
    Db::connection()->getPdo();
    foreach ($statements as $statement) {
        Db::statement($statement);
    }

    Db::table('admin_users')->updateOrInsert(
        ['username' => $username],
        [
            'display_name' => $displayName,
            'password_hash' => $passwordHash,
            'is_active' => true,
        ]
    );

    echo 'Admin users table initialized.' . PHP_EOL;
    echo 'Seeded username: ' . $username . PHP_EOL;
    echo 'Display name: ' . $displayName . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, $exception::class . ': ' . $exception->getMessage() . PHP_EOL);
    exit(1);
}
