<?php declare(strict_types=1);

namespace AutoAdmin\Bundle\Log\Monolog\Handler;

use AutoAdmin\Bundle\Log\Configuration\ConfigManager;
use AutoAdmin\Bundle\Log\Monolog\Client\LogtailClient;
use Monolog\Handler\BufferHandler;
use Monolog\LogRecord;

class LogtailHandler extends BufferHandler
{
    private ConfigManager $configManager;

    /**
     * @param ConfigManager $configManager
     * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
     * @param string $endpoint Logtail ingesting endpoint
     * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
     * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
     */
    public function __construct(
        ConfigManager $configManager,
        bool $bubble = true,
        string $endpoint = LogtailClient::URL,
        int $bufferLimit = 0,
        bool $flushOnOverflow = false
    ) {

        $this->configManager = $configManager;

        parent::__construct(
            new SynchronousLogtailHandler(
                $configManager->getToken(),
                $configManager->getMonologLevel(),
                $bubble,
                $endpoint
            ),
            $bufferLimit,
            $configManager->getMonologLevel(),
            $bubble,
            $flushOnOverflow
        );
    }

    public function handle(array|LogRecord $record): bool
    {
        if (!$this->configManager->logEnabled()) {
            return false;
        }

        return parent::handle($record);
    }
}
