<?php

declare(strict_types=1);

namespace App\Framework\Logging\Handlers;

use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Logging\LogHandler;
use App\Framework\Logging\LogRecord;
use App\Framework\Logging\Metrics\LogMetricsCollector;

/**
 * Metrics Reporting Handler
 *
 * Wrapper der Handler-Performance misst und an Metrics-System meldet.
 */
final readonly class MetricsReportingHandler implements LogHandler
{
    public function __construct(
        private LogHandler $handler,
        private LogMetricsCollector $collector,
        private string $handlerName
    ) {
    }

    public function handle(LogRecord $record): void
    {
        $startTime = Timestamp::now();

        try {
            $this->handler->handle($record);
        } finally {
            $endTime = Timestamp::now();
            $milliseconds = $endTime->diffInMilliseconds($startTime);

            $this->collector->recordHandlerLatency(
                $this->handlerName,
                $milliseconds
            );
        }
    }

    public function isHandling(LogRecord $record): bool
    {
        // Delegate to wrapped handler
        return $this->handler->isHandling($record);
    }
}
