<?php

declare(strict_types=1);

namespace App\Framework\QueryBus;

use App\Framework\Core\AttributeMapper;
use App\Framework\Reflection\WrappedReflectionClass;
use App\Framework\Reflection\WrappedReflectionMethod;

/**
 * Mapper für das QueryHandler-Attribut
 */
final class QueryHandlerMapper implements AttributeMapper
{
    /**
     * Gibt die Attributklasse zurück, die dieser Mapper verarbeitet
     */
    public function getAttributeClass(): string
    {
        return QueryHandler::class;
    }

    /**
     * Implementiert die map-Methode aus dem AttributeMapper-Interface
     */
    public function map(WrappedReflectionClass|WrappedReflectionMethod $reflectionTarget, object $attributeInstance): ?array
    {
        if (! ($reflectionTarget instanceof WrappedReflectionMethod)) {
            return null;
        }

        $parameters = $reflectionTarget->getParameters();

        // Event-Handler müssen mindestens einen Parameter haben (das Event)
        if (count($parameters) < 1) {
            return null;
        }

        $eventType = $parameters[0]->getType();
        if (! $eventType || $eventType->isBuiltin()) {
            return null;
        }

        $eventClassName = $eventType->getName();

        return [
            'class' => $reflectionTarget->getDeclaringClass()->getFullyQualified(),
            'method' => $reflectionTarget->getName(),
            'event_class' => $eventClassName,
            'attribute_data' => [
                'priority' => $attributeInstance->priority ?? 0,
                'stopPropagation' => $attributeInstance->stopPropagation ?? false,
            ],
        ];
    }
}
