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

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

namespace IMATHUZH\Messenger\Example;

require_once dirname(__DIR__) . '/hooks/common.php';

use IMATHUZH\Messenger\AuthorizationToken;

logHeaders('token');

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

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

    $token = $_GET['token'] ?? '';
    if ($token) {
        logmsg("token - INFO - fetching $token");
        try {
            $data = loadTokenStorage(true)->loadToken($token)->toArray();
            logmsg("token - DEBUG - found: " . json_encode($data));
            echo json_encode($data, JSON_PRETTY_PRINT);
        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    } else {
        logmsg("token - INFO - listing all tokens");
        // Initiate session
        openSession(true);
        foreach ($_SESSION[SESSION_KEY] ?? [] as $token => $data) {
            echo "$token: $data\n";
        }
    }

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

    $storage = loadTokenStorage();

    $group = $data->group ?? '';
    $pub = $data->pub ?? '';
    $sub = $data->sub ?? '';
    $ctl = $data->ctl ?? '';

    if ($group !== 'test' && !str_starts_with($group, 'test-')) {
        logmsg("token - ERROR - invalid channel group: $group");
        http_response_code(403);
        die('Only groups "test" and "test-nnn" are supported');
    } elseif ($pub || $sub) {
        logmsg("token - INFO - creating for messenger channel $group: pub = $pub, sub = $sub");
        $token = AuthorizationToken::createMessengerToken($group, $pub, $sub);
    } else {
        logmsg("token - INFO - creating for controller channel for $group:$ctl");
        $token = AuthorizationToken::createControllerToken($group, $ctl);
    }
    echo loadTokenStorage()->saveToken($token);

}

logmsg("token - INFO - done");
