<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\AssignTeacher\AssignTeacherCommand;
use App\Administration\Application\Command\AssignTeacher\AssignTeacherHandler;
use App\Administration\Domain\Exception\AffectationDejaExistanteException;
use App\Administration\Domain\Exception\ClasseNotFoundException;
use App\Administration\Domain\Exception\SubjectNotFoundException;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
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, TeacherAssignmentResource>
 */
final readonly class CreateTeacherAssignmentProcessor implements ProcessorInterface
{
    public function __construct(
        private AssignTeacherHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

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

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

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

        $rawAcademicYearId = $this->academicYearResolver->resolve($data->academicYearId ?? 'current');
        if ($rawAcademicYearId === null) {
            throw new BadRequestHttpException('Identifiant d\'année scolaire invalide.');
        }

        try {
            $command = new AssignTeacherCommand(
                tenantId: $tenantId,
                teacherId: $data->teacherId ?? '',
                classId: $data->classId ?? '',
                subjectId: $data->subjectId ?? '',
                academicYearId: $rawAcademicYearId,
            );

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

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

            return TeacherAssignmentResource::fromDomain($assignment);
        } catch (AffectationDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        } catch (UserNotFoundException|ClasseNotFoundException|SubjectNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('UUID invalide : ' . $e->getMessage());
        }
    }
}
