<?php
/**
 * Bundled minimal Monolog JsonFormatter.
 *
 * Outputs each record as a single JSON line.
 *
 * Original: https://github.com/Seldaek/monolog (MIT)
 */

declare(strict_types=1);

namespace Monolog\Formatter;

final class JsonFormatter
{
    public const BATCH_MODE_NEWLINES = 1;

    public function __construct(
        private readonly int $batchMode = self::BATCH_MODE_NEWLINES,
        private readonly bool $appendNewline = true,
    ) {
    }

    /**
     * @param array<string, mixed> $record
     */
    public function format(array $record): string
    {
        $line = json_encode(
            $record,
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR
        );
        if ($line === false) {
            $line = json_encode([
                'channel'    => $record['channel'] ?? 'unknown',
                'level_name' => $record['level_name'] ?? 'ERROR',
                'message'    => 'log_serialization_failed',
                'datetime'   => $record['datetime'] ?? date('c'),
            ]);
        }
        return $line . ($this->appendNewline ? "\n" : '');
    }
}
