<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\ResendParentInvitation\ResendParentInvitationCommand;
use App\Administration\Application\Command\ResendParentInvitation\ResendParentInvitationHandler;
use App\Administration\Domain\Exception\InvitationDejaActiveeException;
use App\Administration\Domain\Exception\ParentInvitationNotFoundException;
use App\Administration\Infrastructure\Api\Resource\ParentInvitationResource;
use App\Administration\Infrastructure\Security\ParentInvitationVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
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<ParentInvitationResource, ParentInvitationResource>
 */
final readonly class ResendParentInvitationProcessor implements ProcessorInterface
{
    public function __construct(
        private ResendParentInvitationHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

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

        /** @var string $invitationId */
        $invitationId = $uriVariables['id'] ?? '';

        try {
            $command = new ResendParentInvitationCommand(
                invitationId: $invitationId,
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
            );

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

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

            return ParentInvitationResource::fromDomain($invitation);
        } catch (ParentInvitationNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (InvitationDejaActiveeException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
