<?php

declare(strict_types=1);

namespace apexl\Io\modules\logger\services\handlerCreator;

use apexl\Config\ConfigurationInterface;
use apexl\Config\Exceptions\MissingConfigException;
use apexl\Io\modules\logger\dto\handlerConfig;
use apexl\Io\modules\logger\dto\handlerConfigParams\logstashHandlerConfigParams;
use apexl\Io\modules\logger\dto\streamConfig;
use Monolog\Formatter\LogstashFormatter;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\SocketHandler;

final readonly class logstashLogHandlerCreator extends handlerCreator
{
    public function __construct(private ConfigurationInterface $config) {}

    /**
     * @throws MissingConfigException
     */
    public function create(
        string $streamName,
        handlerConfig $handlerConfig,
        streamConfig $streamConfig,
    ): HandlerInterface {
        /** @var logstashHandlerConfigParams $params */
        $params = $handlerConfig->params;
        $connectionString = sprintf(
            '%s:%s',
            $params->host,
            $params->port
        );

        $handler = new SocketHandler($connectionString, $this->level($handlerConfig, $streamConfig));

        $handler->setFormatter(
            new LogstashFormatter(
                $params->application ?? $this->config->get('app.site.name'),
                $params->system,
            )
        );

        return $handler;
    }
}
