<?php
declare(strict_types=1);

function ensure_default_admin(): void
{
    static $ran = false;
    if ($ran) {
        return;
    }
    $ran = true;

    $username = getenv('ADMIN_USERNAME') ?: 'admin';
    $password = getenv('ADMIN_PASSWORD') ?: 'Admin123!';
    $fullName = getenv('ADMIN_FULLNAME') ?: 'System Administrator';
    $email = getenv('ADMIN_EMAIL') ?: 'admin@example.com';
    $resetFlag = getenv('ADMIN_RESET_PASSWORD');
    $shouldReset = $resetFlag === false ? true : filter_var($resetFlag, FILTER_VALIDATE_BOOLEAN);

    try {
        $pdo = db();
        $stmt = $pdo->prepare('SELECT id, password FROM users WHERE username = :username LIMIT 1');
        $stmt->execute(['username' => $username]);
        $user = $stmt->fetch();

        if (!$user) {
            $insert = $pdo->prepare(
                'INSERT INTO users (username, password, role, full_name, email, status)
                 VALUES (:username, :password, :role, :full_name, :email, 1)'
            );
            $insert->execute([
                'username' => $username,
                'password' => password_hash($password, PASSWORD_BCRYPT),
                'role' => 'admin',
                'full_name' => $fullName,
                'email' => $email,
            ]);
            return;
        }

        if ($shouldReset && !password_verify($password, $user['password'])) {
            $update = $pdo->prepare('UPDATE users SET password = :password, status = 1 WHERE id = :id');
            $update->execute([
                'password' => password_hash($password, PASSWORD_BCRYPT),
                'id' => $user['id'],
            ]);
        }
    } catch (Throwable $exception) {
        throw $exception;
    }
}
