<?php

namespace NoahVet\Reef\Log;

use Monolog\Handler\SyslogUdp\UdpSocket;
use NoahVet\Reef\Domain\Log\SyslogMessage;
use NoahVet\Reef\Log\Formater\LogFormaterInterface;
use NoahVet\Reef\Log\Formater\Rfc5424Formater;
use Psr\Clock\ClockInterface;

class SyslogClient implements SyslogClientInterface
{
    private UdpSocket $socket;

    private readonly LogFormaterInterface $logFormater;

    public function __construct(
        protected readonly string $reefAppName,
        protected readonly string $logUrl,
        ClockInterface $clock,
    ) {
        $this->logFormater = new Rfc5424Formater($this->reefAppName, $clock);

        $urlParts = \parse_url($this->logUrl);

        if (!\is_array($urlParts)) {
            throw new \Exception('Invalid log url : '.$this->logUrl);
        }

        $this->socket = new UdpSocket($urlParts['host'] ?? '', $urlParts['port'] ?? 6514);
    }

    #[\Override]
    public function sendMessage(SyslogMessage $syslogMessage): void
    {
        $this->socket->write($this->logFormater->format($syslogMessage));

        $this->socket->close();
    }
}
