<?php

it('creates auth tokens and reports missing customer users clearly', function (): void {
    $script = tempnam(sys_get_temp_dir(), 'truckwash-create-token-') . '.php';
    $appRoot = addslashes(WD);
    file_put_contents($script, str_replace('__APP_ROOT__', $appRoot, <<<'PHP'
<?php

namespace {
    define('WD', '__APP_ROOT__');
}

namespace objects {
    class users_o
    {
        public int $id;
        public static array $existing = [];

        public function getUserByCustomerNumber(int $customer_number): self
        {
            if (in_array($customer_number, self::$existing, true)) {
                $this->id = 123;
            }

            return $this;
        }

        public function exists(): bool
        {
            return isset($this->id) && $this->id > 0;
        }
    }

    class tokens_o
    {
        public static array $created = [];

        public function create(int $user_id, string $token, string $type = 'AUTH_TOKEN'): void
        {
            self::$created[] = compact('user_id', 'token', 'type');
        }
    }
}

namespace {
    require_once WD . '/interfaces/authentication_i.php';
    require_once WD . '/classes/authentication.php';

    $result = [
        'success_token' => null,
        'created' => [],
        'missing_error' => null,
    ];

    \objects\users_o::$existing = [111111];
    \objects\tokens_o::$created = [];
    $result['success_token'] = (new \classes\authentication())->create_token(111111);
    $result['created'] = \objects\tokens_o::$created;

    \objects\users_o::$existing = [];
    try {
        (new \classes\authentication())->create_token(222222);
    } catch (\Throwable $exception) {
        $result['missing_error'] = $exception->getMessage();
    }

    echo json_encode($result, JSON_THROW_ON_ERROR);
}
PHP));

    try {
        $output = [];
        $exitCode = 0;
        exec(PHP_BINARY . ' ' . escapeshellarg($script), $output, $exitCode);

        expect($exitCode)->toBe(0);
        $result = json_decode(implode("\n", $output), true, 512, JSON_THROW_ON_ERROR);

        expect($result['success_token'])->toBeString()->toMatch('/^[a-f0-9]{64}$/')
            ->and($result['created'])->toHaveCount(1)
            ->and($result['created'][0]['user_id'])->toBe(123)
            ->and($result['created'][0]['type'])->toBe('AUTH_TOKEN')
            ->and($result['missing_error'])->toBe('User not found for customer number: 222222');
    } finally {
        if (is_file($script)) {
            unlink($script);
        }
    }
});
