<?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 class(REST_BASE_URL, [
    '/token/merge/' => [
        'POST' => function(RequestInterface $request): mixed {
            $tokenStorage = loadTokenStorage();
            logTokens('rest');
            $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
            );
            logmsg('rest - INFO - merging tokens');
            $merged = AuthorizationToken::mergeTokens(...$tokens);
            $mergedId = $tokenStorage->saveToken($merged, $body->merged ?? '');
            logmsg("rest - INFO - merged tokens into $mergedId");
            return $mergedId;
        } ],
    '/token/channels/' => [
        'GET' => function(RequestInterface $request): mixed {
            [ $tokenId, $group ] = $request->getParams('/^\w+$/', '/^[\w\-]+$/');
            logmsg("rest - DEBUG - loading $group from $tokenId");
            $tokenStorage = loadTokenStorage(false);
            logTokens('rest');
            return $tokenStorage->loadToken($tokenId)->toArray()[$group] ?? [];
        } ],
    '/token/groups/' => [
        'GET' => function(RequestInterface $request): mixed {
            $tokenId = $request->getParams('/^\w+$/')[0];
            logmsg("rest - DEBUG - loading groups of $tokenId");
            $tokenStorage = loadTokenStorage(false);
            logTokens('rest');
            return $tokenStorage->loadToken($tokenId)->toArray();
        } ],
    '/token/' => [
        'GET' => function(RequestInterface $request): mixed {
            $tokenId = $request->getParams('/^\w+$/')[0];
            logmsg("rest - DEBUG - loading channel data of $tokenId");
            $tokenStorage = loadTokenStorage(false);
            logTokens('rest');
            return $tokenStorage->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
            ];
        } ]
]) extends RestProcessor {
    protected function handleException(\Throwable $e): void
    {
        logmsg("rest - ERROR - " . $e->getMessage());
        parent::handleException($e);
    }
};

logHeaders('rest');
$app->process(RestRequest::fromGlobals());
logmsg('rest - INFO - done');
