<?php declare(strict_types=1);

namespace AutoAdmin\Bundle\Log\Monolog\Handler;

use AutoAdmin\Bundle\Log\Monolog\Client\LogtailClient;
use AutoAdmin\Bundle\Log\Monolog\Formatter\LogtailFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Processor\HostnameProcessor;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\ProcessIdProcessor;
use Monolog\Processor\WebProcessor;

class SynchronousLogtailHandler extends AbstractProcessingHandler {
    private ?LogtailClient $client;

    public function __construct(
        ?string $sourceToken,
        Level $level = Level::Debug,
        bool $bubble = true,
        string $endpoint = LogtailClient::URL
    ) {
        parent::__construct($level, $bubble);


        $this->client = $sourceToken ? new LogtailClient($sourceToken, $endpoint) : null;

        $this->pushProcessor(new IntrospectionProcessor($level, ['Logtail\\']));
        $this->pushProcessor(new WebProcessor);
        $this->pushProcessor(new ProcessIdProcessor);
        $this->pushProcessor(new HostnameProcessor);
    }

    protected function write(array|LogRecord $record): void {
        if ($this->client) {
            $this->client->send($record["formatted"]);
        }
    }

    public function handleBatch(array $records): void
    {
        if ($this->client) {
            $formattedRecords = $this->getFormatter()->formatBatch($records);
            $this->client->send($formattedRecords);
        }
    }

    protected function getDefaultFormatter(): FormatterInterface
    {
        return new LogtailFormatter();
    }

    public function getFormatter(): FormatterInterface
    {
        return $this->getDefaultFormatter();
    }
}
