<?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;

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

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

    $token = $_GET['token'] ?? '';
    if ($token) {
        try {
            $data = loadTokenStorage(true)->loadToken($token)->toArray();
            echo json_encode($data, JSON_PRETTY_PRINT);
        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    } else {
        // 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-')) {
        http_response_code(403);
        die('Only groups "test" and "test-nnn" are supported');
    } elseif ($pub || $sub) {
        $token = AuthorizationToken::createMessengerToken($group, $pub, $sub);
    } else {
        $token = AuthorizationToken::createControllerToken($group, $ctl);
    }
    echo loadTokenStorage()->saveToken($token);

}
