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

// A helper script for testing messenger tokens
//  * creating tokens
//  * listing tokens
//  * merging tokens

use IMATHUZH\Messenger\Constants;
use IMATHUZH\Messenger\AuthorizationToken;
use IMATHUZH\Messenger\SessionTokenManager;

use function IMATHUZH\Messenger\logHeaders;
use function IMATHUZH\Messenger\logmsg;

require_once __DIR__ . '/php/Classes/Constants.php';
require_once __DIR__ . '/php/Classes/TokenInterface.php';
require_once __DIR__ . '/php/Classes/AuthorizationToken.php';
require_once __DIR__ . '/php/Classes/TokenManagerInterface.php';
require_once __DIR__ . '/php/Classes/AbstractTokenManager.php';
require_once __DIR__ . '/php/Classes/SessionTokenManager.php';
require_once __DIR__ . '/hooks/logging.php';


logHeaders('token');

// Initiate session
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    http_response_code(200);
    header('Content-Type: text/plain');

    $token = $_GET['token'] ?? '';
    if ($token) {
        logmsg("token - INFO - fetching $token");
        $manager = new SessionTokenManager($_SESSION);
        try {
            $data = $manager->loadToken($token);
            logmsg("token - DEBUG - found: " . json_encode($data->toArray()));
            echo json_encode($data->toArray(), JSON_PRETTY_PRINT);
        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    } else {
        logmsg("token - INFO - listing all tokens");
        foreach ($_SESSION as $token => $data) {
            if (strlen($token) === Constants::TOKEN_SIZE * 2) {
                echo "$token: $data\n";
            }
        }
    }

} else {
    
    $data = json_decode(file_get_contents('php://input'), true);
    if (!$data) {
        http_response_code(400);
        die('Invalid request');
    }

    $manager = new SessionTokenManager($_SESSION);

    $group = $data['group'] ?? '';
    $pub = $data['pub'] ?? '';
    $sub = $data['sub'] ?? '';
    $ctl = $data['ctl'] ?? '';
    if ($pub || $sub) {
        logmsg("token - INFO - creating for messenger channel $group: pub = $pub, sub = $sub");
        $token = AuthorizationToken::createMessengerToken($group, $pub, $sub);
        echo $manager->saveToken($token);
    } else {
        logmsg("token - INFO - creating for controller channel for $group:$ctl");
        $token = AuthorizationToken::createControllerToken($group, $ctl);
        echo $manager->saveToken($token);
    }

}

logmsg("token - INFO - done");
