<?php declare(strict_types=1);
/**
 * @package messenger
 * @author kputyr
 * @date 21.04.2026
 */

/**************************************************************
 * Configuration constants
 * 
 * Please modify as needed
 **************************************************************/

const SESSION_COOKIE = 'qfq';
const SESSION_KEY = 'qfq';
const REST_BASE_URL = '/messenger/rest/';

/* Common part for hooks. Do not modify unless you know exactly what you are doing. */

use IMATHUZH\Messenger\TokenStorage;
use IMATHUZH\Messenger\TokenStorageInterface;

/* Class autoloader for hooks */

spl_autoload_register(function($className) {
    $classPath = strtr($className, '\\', '/');
    if (str_starts_with($classPath, 'Psr/Log/')) {
        include __DIR__ . '/vendor/psr/log/src/' . substr($classPath, 8) . '.php';
    } elseif (str_starts_with($classPath, 'IMATHUZH/Messenger/')) {
        include dirname(__DIR__) . '/php/Classes/' . substr($classPath, 19) . '.php';
    } else {
        trigger_error("class not found: $className");
    }
});

/**
 * A helper function to immediately reject a request
 */
function reject(string $message): bool
{
    throw new \Exception($message);    
}

/**
 * Opens a PHP session unless one is already active or $_SESSION array
 * exists and read-only access has been requested.
 * 
 * @param bool $readonly   if true, then the session is closed immediately
 *                         after populating $_SESSION array
 */
function openSession(bool $readonly=false): void
{
    if (session_status() !== PHP_SESSION_ACTIVE || !($readonly && isset($_SESSION))) {
        session_name(SESSION_COOKIE);
        session_start(['read_and_close' => $readonly]);
    }
    if (!isset($_SESSION[SESSION_KEY])) {
        $_SESSION[SESSION_KEY] = [];
    }
}

/**
 * Creates a new TokenStorage instance using the QFQ session for storage.
 * 
 * The following sources for tokens are used:
 *  + SIP store (read and write)
 *  + U store (readonly)
 *  + W store (readonly)
 * 
 * A PHP session is started when needed.
 * 
 * @param bool $readonly   if true, then the session is closed immediately
 *                         after populating $_SESSION array
 */
function loadTokenStorage(bool $readonly=false): TokenStorageInterface
{
    openSession($readonly);
    return new TokenStorage(
        $_SESSION[SESSION_KEY],
        unserialize($_SESSION[SESSION_KEY]['store-U'] ?? '') ?: [],
        unserialize($_SESSION[SESSION_KEY]['store-W'] ?? '') ?: []
    );
}
