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

namespace IMATHUZH\Messenger\Hooks;

/**************************************************************
 * 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;

require_once dirname(__DIR__) . '/vendor/composer/autoload.php';

/**
 * 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'] ?? '') ?: []
    );
}
