<?php

declare(strict_types=1);

namespace App\Framework\Process\ValueObjects\Logs;

/**
 * Einzelner Log-Eintrag.
 */
final readonly class LogEntry
{
    public function __construct(
        public string $level,
        public string $message,
        public ?\DateTimeImmutable $timestamp = null,
        public ?string $context = null
    ) {
    }

    /**
     * Erstellt einen Log Entry aus einer Log-Zeile.
     */
    public static function fromLine(string $line): self
    {
        // Versuche Standard-Format zu parsen: [timestamp] level: message
        if (preg_match('/^\[([^\]]+)\]\s+(\w+):\s+(.+)$/', $line, $matches)) {
            return new self(
                level: strtoupper($matches[2]),
                message: $matches[3],
                timestamp: new \DateTimeImmutable($matches[1])
            );
        }

        // Fallback: Ganzer Line als Message
        return new self(
            level: 'UNKNOWN',
            message: $line
        );
    }

    /**
     * Prüft, ob es ein Error-Level ist.
     */
    public function isError(): bool
    {
        return in_array($this->level, ['ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'], true);
    }

    /**
     * Prüft, ob es ein Warning-Level ist.
     */
    public function isWarning(): bool
    {
        return $this->level === 'WARNING';
    }

    /**
     * Konvertiert zu Array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'level' => $this->level,
            'message' => $this->message,
            'timestamp' => $this->timestamp?->format('Y-m-d H:i:s'),
            'context' => $this->context,
        ];
    }
}
