<?php

declare(strict_types=1);

namespace App\Framework\CommandBus;

use App\Framework\Core\AttributeCompiler;

final readonly class CommandHandlerCompiler implements AttributeCompiler
{
    public function getAttributeClass(): string
    {
        return CommandHandler::class;
    }

    public function compile(array $handlers): array
    {
        $compiledHandlers = [];

        foreach ($handlers as $handler) {
            $className = $handler['class'];
            $methodName = $handler['method'];

            // Ermittle den Command-Typ aus dem ersten Parameter der Methode
            $methodInfo = new \ReflectionMethod($className, $methodName);
            $parameters = $methodInfo->getParameters();

            if (count($parameters) > 0) {
                $paramType = $parameters[0]->getType();
                if ($paramType instanceof \ReflectionNamedType) {
                    $commandClass = $paramType->getName();

                    // Speichere den Handler für diesen Command-Typ
                    $compiledHandlers[$commandClass] = [
                        'class' => $className,
                        'method' => $methodName,
                    ];
                }
            }
        }

        return $compiledHandlers;
    }
}
