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

// set up autoload
include 'autoload.php';

use IMATHUZH\Messenger\MessageDispatcher;
use IMATHUZH\Messenger\HttpPublisher;
use IMATHUZH\Messenger\Nchan\NchanRequest;
use IMATHUZH\Messenger\TouchPublisher;

// Collect data
$data = json_decode(file_get_contents('php://input'));

$name = $data->name ?? '';
$channels = $data->channels ?? [];
$payload = $data->payload ?? null;
if (empty($channels)) exit;

// Update special channels
$channels = array_map(
    function ($ch) use ($name) {
        switch ($ch) {
            case 'table': return "t_$name";
            case 'page': return "p_$name";
            case 'error': return "e_$name";
            default: return $ch;
        }
    },
    $channels
);

// For testing - send control info to the controller
$request = new NchanRequest('http://localhost:8080', '', 'http', '');
$request->setChannelGroup('test')
        ->setPubChannels($channels)
        ->generateUrls();
$request->notifyController('post', ['data' => $payload]);

// Create the dispatcher
$dispatcher = new MessageDispatcher();
$dispatcher->addPublisher(new HttpPublisher('http://localhost:8080/messenger/test/pub/:pub:'));
$dispatcher->addPublisher(new TouchPublisher('/var/www/html/messenger/signals', [
    'p' => 'page',
    't' => '',
    'e' => 'throw/an/error'
]));

// Publish the message
$errors = $dispatcher->publishMessage(
    $channels,
    $name,
    $payload
);

// Display errors
echo "Post($name, ", implode('|', $channels), ') errors:', PHP_EOL;

foreach($errors as $error) {
    echo '  [', $error->publisher::class, '] ',
              $error->key, ':', PHP_EOL,
              '    ', $error->message, PHP_EOL;
}
