<?php
// Lightweight CLI test for authentication::create_token behavior when user is missing
namespace {
    if (!defined('WD')) { define('WD', dirname(__DIR__, 2)); }
}

// Provide stubs for required objects to avoid DB/config dependencies
namespace objects {
    class users_o {
        public int $id; // intentionally typed, uninitialized unless set
        public static array $existing = [];
        public function getUserByCustomerNumber(int $customer_number): self {
            if (in_array($customer_number, self::$existing, true)) {
                $this->id = 123; // simulate existing user id
            }
            return $this;
        }
        public function exists(): bool {
            // Exists iff id was set and > 0
            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';

    function ok(string $m): void { echo "\033[32m✔ $m\033[0m\n"; }
    function fail(string $m): void { echo "\033[31m✖ $m\033[0m\n"; }

    $auth = new \classes\authentication();

    // Case 1: existing user → should return a 64-hex token
    \objects\users_o::$existing = [111111];
    $t1 = $auth->create_token(111111);
    if (is_string($t1) && preg_match('/^[a-f0-9]{64}$/', $t1)) {
        ok('create_token succeeds for existing user and returns hex token');
    } else {
        fail('create_token did not return expected token for existing user');
    }

    // Case 2: missing user → before fix this fatals (typed property access); after fix it should throw Exception
    \objects\users_o::$existing = [];
    try {
        $auth->create_token(222222);
        fail('create_token should throw when user is missing');
    } catch (\Exception $e) {
        ok('create_token throws a clear Exception when user is missing');
    } catch (\Error $e) {
        fail('Fatal error (typed property access) encountered: ' . $e->getMessage());
    }

    echo "CreateTokenUserNotFoundTest completed.\n";
}
