<?php
declare(strict_types=1);

namespace App\Framework\Logging\Handlers;

use App\Framework\Logging\LogHandler;
use App\Framework\Logging\LogLevel;
use App\Framework\Logging\LogRecord;

final class WebHandler implements LogHandler
{
    public function __construct(
        private readonly LogLevel $minLevel = LogLevel::DEBUG,
        private readonly bool $debugOnly = true
    ) {}

    public function isHandling(LogRecord $record): bool
    {
        // Nur bei Web-Requests (nicht CLI)
        if (PHP_SAPI === 'cli') {
            return false;
        }

        // Debug-Modus-Check
        if ($this->debugOnly && !filter_var(getenv('APP_DEBUG'), FILTER_VALIDATE_BOOLEAN)) {
            return false;
        }

        return $record->getLevel()->value >= $this->minLevel->value;
    }

    public function handle(LogRecord $record): void
    {
        $timestamp = $record->getFormattedTimestamp();
        $level = $record->getLevel()->getName();
        $message = $record->getMessage();
        $channel = $record->getChannel();

        // Request-ID falls vorhanden
        $requestId = $record->hasExtra('request_id')
            ? "[{$record->getExtra('request_id')}] "
            : '';

        // Channel falls vorhanden
        $channelPrefix = $channel ? "[$channel] " : '';

        $logLine = sprintf(
            '[%s] %s[%s] %s%s',
            $timestamp,
            $requestId,
            $level,
            $channelPrefix,
            $message
        );

        // Context-Daten falls vorhanden
        $context = $record->getContext();
        if (!empty($context)) {
            $logLine .= ' | Context: ' . json_encode($context, JSON_UNESCAPED_SLASHES);
        }

        // In error_log schreiben
        error_log($logLine);
    }

}
