<?php

namespace IMATHUZH\Qfq\Core\Helper;

use IMATHUZH\Messenger\HttpPublisher;
use IMATHUZH\Messenger\MessageDispatcher;
use IMATHUZH\Qfq\Core\Store\Store;

/**
 * Thin adapter over the upstream nchan-messages MessageDispatcher/HttpPublisher.
 *
 * Centralises how QFQ talks to the server-side nchan publisher endpoint so
 * there is exactly one place that knows the URL pattern, reads the publish
 * base URL from the system store and joins it with the messenger group. All
 * server-initiated publishing (Chat notifications, form message parameter)
 * goes through this helper.
 *
 * The target is the auth-less `messenger-local.conf` location bound to the
 * loopback or trusted network by the admin — no token needed on the PHP→nchan
 * hop. `SYSTEM_MESSENGER_PUBLISH_URL` is the base (e.g. `http://127.0.0.1/messenger/`)
 * and the HTTP POST lands at `<base>/<group>/pub/<channels>`.
 */
class MessengerPublisher {

    /**
     * Posts a message to one or more channels on the nchan publisher endpoint.
     *
     * Silent no-op when the publisher URL is not configured or no channels
     * were passed — callers can opt in to treating publish failures as fatal
     * by inspecting the returned error list.
     *
     * @param string $group     messenger group (nchan channel group)
     * @param array  $channels  target channel names
     * @param string $name      message name delivered to subscribers
     * @param mixed  $payload   JSON-serialisable payload delivered to subscribers
     * @return array            list of upstream publisher errors — empty on success
     *                          or when publishing is disabled
     */
    public static function publish(string $group, array $channels, string $name, $payload): array {
        if (empty($channels)) {
            return [];
        }
        $publishUrl = Store::getVar(SYSTEM_MESSENGER_PUBLISH_URL, STORE_SYSTEM) ?: '';
        if ($publishUrl === '') {
            return [];
        }
        // HttpPublisher replaces :pub: with the comma-joined channel list.
        $urlPattern = rtrim($publishUrl, '/') . '/' . $group . '/pub/:pub:';
        return (new MessageDispatcher())
            ->addPublisher(new HttpPublisher($urlPattern))
            ->publishMessage($channels, $name, $payload);
    }
}
