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

use IMATHUZH\Messenger\AuthorizationToken;
use IMATHUZH\Messenger\Rest\RequestInterface;
use IMATHUZH\Messenger\Rest\RestProcessor;
use IMATHUZH\Messenger\Rest\RestRequest;

require_once 'common.php';

$app = new RestProcessor(REST_BASE_URL, [
    '/token/merge/' => [
        'POST' => function(RequestInterface $request): mixed {
            $tokenStorage = loadTokenStorage();
            $body = $request->getBody();
            $tokens = array_filter(
                array_map(
                    function($tokenId) use($tokenStorage) {
                        $trimmedId = trim($tokenId);
                        return $trimmedId ? $tokenStorage->loadToken($trimmedId) : null;
                    },
                    $body->tokens ?? []
                ), fn ($token) => !!$token
            );
            $merged = AuthorizationToken::mergeTokens(...$tokens);
            $mergedId = $tokenStorage->saveToken($merged, $body->merged ?? '');
            return $mergedId;
        } ],
    '/token/channels/' => [
        'GET' => function(RequestInterface $request): mixed {
            [ $tokenId, $group ] = $request->getParams('/^\w+$/', '/^[\w\-]+$/');
            return loadTokenStorage(true)->loadToken($tokenId)->toArray()[$group] ?? [];
        } ],
    '/token/groups/' => [
        'GET' => function(RequestInterface $request): mixed {
            $tokenId = $request->getParams('/^\w+$/')[0];
            return array_keys(loadTokenStorage(true)->loadToken($tokenId)->toArray());
        } ],
    '/token/' => [
        'GET' => function(RequestInterface $request): mixed {
            $tokenId = $request->getParams('/^\w+$/')[0];
            return loadTokenStorage(true)->loadToken($tokenId)->toArray();
        } ],
    '/test/' => [
        'GET' => function(RequestInterface $request): mixed {
            openSession(true);
            $sip = $request->getParams()[0] ?? '';
            if (preg_match('/\w{13}/', $sip)) {
                $content = $_SESSION['qfq'][$sip] ?? '(empty)';
            } elseif ($sip) {
                $content = '(invalid)';
            } else {
                $content = '(none)';
            }
            return [
              'cookie' => $_SERVER['HTTP_COOKIE'] ?? null,
              'host' => $_SERVER['HTTP_HOST'] ?? null,
              'remote-ip' => $_SERVER['REMOTE_ADDR'] ?? null,
              'sip' => $content
            ];
        } ]
]);

$app->process(RestRequest::fromGlobals());
