<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\SendParentInvitation\SendParentInvitationCommand;
use App\Administration\Application\Command\SendParentInvitation\SendParentInvitationHandler;
use App\Administration\Domain\Exception\EmailInvalideException;
use App\Administration\Infrastructure\Api\Resource\ParentInvitationResource;
use App\Administration\Infrastructure\Security\ParentInvitationVoter;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
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 SendParentInvitationProcessor implements ProcessorInterface
{
    public function __construct(
        private SendParentInvitationHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private Security $security,
    ) {
    }

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

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

        $currentUser = $this->security->getUser();
        if (!$currentUser instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Utilisateur non authentifié.');
        }

        try {
            $command = new SendParentInvitationCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                studentId: $data->studentId ?? '',
                parentEmail: $data->parentEmail ?? '',
                createdBy: $currentUser->userId(),
            );

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

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

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