<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Scolarite\Application\Command\DeleteScheduleSlot\DeleteScheduleSlotCommand;
use App\Scolarite\Application\Command\DeleteScheduleSlot\DeleteScheduleSlotHandler;
use App\Scolarite\Domain\Exception\ScheduleSlotNotFoundException;
use App\Scolarite\Infrastructure\Api\Resource\ScheduleSlotResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
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;

/**
 * Processor API Platform pour supprimer un créneau d'emploi du temps.
 *
 * @implements ProcessorInterface<ScheduleSlotResource, null>
 */
final readonly class DeleteScheduleSlotProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteScheduleSlotHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @param ScheduleSlotResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::DELETE)) {
            throw new AccessDeniedHttpException("Vous n'êtes pas autorisé à supprimer des créneaux.");
        }

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

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

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

        try {
            $command = new DeleteScheduleSlotCommand(
                tenantId: $tenantId,
                slotId: $slotId,
            );

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

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

            return null;
        } catch (ScheduleSlotNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Créneau non trouvé.');
        }
    }
}
