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

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

namespace IMATHUZH\Messenger\Example;

require_once __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");
        $storage = loadTokenStorage();
        try {
            $data = $storage->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");
        // Initiate session
        session_start();
        foreach ($_SESSION[SESSION_KEY] ?? [] as $token => $data) {
            echo "$token: $data\n";
        }
    }

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

    $storage = loadTokenStorage();

    $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 $storage->saveToken($token);
    } else {
        logmsg("token - INFO - creating for controller channel for $group:$ctl");
        $token = AuthorizationToken::createControllerToken($group, $ctl);
        echo $storage->saveToken($token);
    }

}

logmsg("token - INFO - done");
