<?php

declare(strict_types=1);

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

use apexl\Io\modules\logger\dto\handlerConfig;
use apexl\Io\modules\logger\dto\handlerConfigParams\fileHandlerConfigParams;
use apexl\Io\modules\logger\dto\streamConfig;
use apexl\Io\services\FilePaths;
use Monolog\Handler\RotatingFileHandler;

final readonly class fileLogHandlerCreator extends handlerCreator
{
    public function __construct(private FilePaths $filePaths) {}

    public function create(
        string $streamName,
        handlerConfig $handlerConfig,
        streamConfig $streamConfig
    ): RotatingFileHandler {
        /** @var fileHandlerConfigParams $params */
        $params = $handlerConfig->params;
        $file = $params->file ?? sprintf('%s.log', $streamName);
        if (!str_starts_with($file, '/')) {
            $file = $this->filePaths->basePath(sprintf('%s/%s', $streamConfig->logDirectory, $file));
        }

        return new RotatingFileHandler($file, $params->maxFiles ?? 7, $this->level($handlerConfig, $streamConfig));
    }
}
