<?php

namespace AutoAdmin\Bundle\Log\Monolog\Formatter;

use Monolog\Formatter\JsonFormatter;
use Monolog\LogRecord;

class LogtailFormatter extends JsonFormatter
{
    public function __construct() {
        parent::__construct(self::BATCH_MODE_JSON, false);
        $this->setMaxNormalizeItemCount(PHP_INT_MAX);
    }

    public function format(array|LogRecord $record): string {
        return parent::format(self::formatRecord($record));
    }

    public function formatBatch(array $records): string
    {
        $normalized = array_values($this->normalize(array_map('self::formatRecord', $records)));
        return $this->toJson($normalized, true);
    }

    protected static function formatRecord(array $record): array
    {
        return [
            'dt' => $record['datetime'],
            'message' => $record['message'],
            'level' => $record['level_name'],
            'monolog' => [
                'channel' => $record['channel'],
                'context' => $record['context'],
                'extra' => $record['extra'],
            ],
        ];
    }
}
