<?php

declare(strict_types=1);

namespace Apexl\Io\Logger\Services\HandlerCreator;

use Apexl\Config\ConfigurationInterface;
use Apexl\Config\Exceptions\MissingConfigException;
use Apexl\Io\Logger\Dtos\HandlerConfig;
use Apexl\Io\Logger\Dtos\HandlerConfigParams\LogstashHandlerConfigParams;
use Apexl\Io\Logger\Dtos\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;
    }
}
