<?php

declare(strict_types=1);

namespace App\Framework\CommandBus\Middleware;

use App\Framework\CommandBus\Middleware;
use App\Framework\Performance\Contracts\PerformanceCollectorInterface;
use App\Framework\Performance\PerformanceCategory;

final readonly class PerformanceMonitoringMiddleware implements Middleware
{
    public function __construct(
        private PerformanceCollectorInterface $collector
    ) {
    }

    public function handle(object $command, callable $next): mixed
    {
        $commandKey = 'command_' . basename(str_replace('\\', '/', $command::class));

        $this->collector->startTiming($commandKey, PerformanceCategory::SYSTEM, [
            'command_class' => $command::class,
        ]);

        $result = $next($command);

        $this->collector->endTiming($commandKey);

        return $result;
    }
}
