<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\RemoveAssignment\RemoveAssignmentCommand;
use App\Administration\Application\Command\RemoveAssignment\RemoveAssignmentHandler;
use App\Administration\Domain\Exception\AffectationNotFoundException;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProcessorInterface<TeacherAssignmentResource, null>
 */
final readonly class RemoveTeacherAssignmentProcessor implements ProcessorInterface
{
    public function __construct(
        private RemoveAssignmentHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @param TeacherAssignmentResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        if (!$this->authorizationChecker->isGranted(TeacherAssignmentVoter::DELETE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à retirer une affectation.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string|null $assignmentId */
        $assignmentId = $uriVariables['id'] ?? null;
        if ($assignmentId === null) {
            throw new NotFoundHttpException('Affectation non trouvée.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        try {
            $command = new RemoveAssignmentCommand(
                assignmentId: $assignmentId,
                tenantId: $tenantId,
            );

            $assignment = ($this->handler)($command);

            foreach ($assignment->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return null;
        } catch (AffectationNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Affectation non trouvée.');
        }
    }
}
