<?php

namespace AutoAdmin\Bundle\Log\Monolog\Formatter;

use Monolog\Formatter\JsonFormatter;
use Monolog\Formatter\NormalizerFormatter;
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(LogRecord $record): string
    {
        $normalized = NormalizerFormatter::normalize(self::formatRecord($record));

        if (isset($normalized['context']) && $normalized['context'] === []) {
            if ($this->ignoreEmptyContextAndExtra) {
                unset($normalized['context']);
            } else {
                $normalized['context'] = new \stdClass;
            }
        }
        if (isset($normalized['extra']) && $normalized['extra'] === []) {
            if ($this->ignoreEmptyContextAndExtra) {
                unset($normalized['extra']);
            } else {
                $normalized['extra'] = new \stdClass;
            }
        }

        return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : '');
    }

    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(LogRecord $record): array
    {
        return [
            'dt' => $record->datetime,
            'message' => $record->message,
            'level' => $record->level->getName(),
            'monolog' => [
                'channel' => $record->channel,
                'context' => $record->context,
                'extra' => $record->extra,
            ],
        ];
    }
}
