<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Domain\Exception\TenantMismatchException;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Command\DesignateReplacement\DesignateReplacementCommand;
use App\Scolarite\Application\Command\DesignateReplacement\DesignateReplacementHandler;
use App\Scolarite\Domain\Exception\DatesRemplacementInvalidesException;
use App\Scolarite\Domain\Exception\RemplacementSameTeacherException;
use App\Scolarite\Domain\Exception\UtilisateurNonEnseignantException;
use App\Scolarite\Infrastructure\Api\Resource\TeacherReplacementResource;
use App\Scolarite\Infrastructure\Security\TeacherReplacementVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Bundle\SecurityBundle\Security;
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<TeacherReplacementResource, TeacherReplacementResource>
 */
final readonly class CreateTeacherReplacementProcessor implements ProcessorInterface
{
    public function __construct(
        private DesignateReplacementHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private Security $security,
    ) {
    }

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

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

        $user = $this->security->getUser();

        if (!$user instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        try {
            $command = new DesignateReplacementCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                replacedTeacherId: $data->replacedTeacherId ?? '',
                replacementTeacherId: $data->replacementTeacherId ?? '',
                startDate: $data->startDate ?? '',
                endDate: $data->endDate ?? '',
                classes: $data->classes ?? [],
                reason: $data->reason,
                createdBy: $user->userId(),
            );

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

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

            return TeacherReplacementResource::fromDomain($replacement);
        } catch (RemplacementSameTeacherException|DatesRemplacementInvalidesException|TenantMismatchException|UtilisateurNonEnseignantException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('UUID invalide : ' . $e->getMessage());
        }
    }
}
