<?php
namespace EasyChat\Library\Messenger;









class OutboundDispatchGuard {

    private $registry;
    private $logger;

    public function __construct($registry) {
        $this->registry = $registry;
        $this->logger = new MessengerLogger($registry);
    }

    public function sendMessageId(int $message_id): array {
        $buffer_level = ob_get_level();
        $noise = '';
        ob_start();

        try {
            $outbound = new OutboundService($this->registry);
            $result = $outbound->sendMessageId($message_id);
        } catch (\Throwable $e) {
            $result = ['success' => false, 'error' => 'outbound_exception'];
            $this->logger->warning('messenger_outbound_exception', [
                'message_id' => $message_id,
                'class' => get_class($e),
            ]);
        }

        while (ob_get_level() > $buffer_level) {
            $chunk = ob_get_clean();
            $noise = (is_string($chunk) ? $chunk : '') . $noise;
        }

        if ($noise !== '') {
            $this->logger->warning('messenger_outbound_output', [
                'message_id' => $message_id,
                'bytes' => strlen($noise),
            ]);
        }

        return is_array($result) ? $result : ['success' => false, 'error' => 'outbound_bad_result'];
    }
}
