<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\LinkParentToStudent\LinkParentToStudentCommand;
use App\Administration\Application\Command\LinkParentToStudent\LinkParentToStudentHandler;
use App\Administration\Domain\Exception\InvalidGuardianRoleException;
use App\Administration\Domain\Exception\InvalidStudentRoleException;
use App\Administration\Domain\Exception\LiaisonDejaExistanteException;
use App\Administration\Domain\Exception\MaxGuardiansReachedException;
use App\Administration\Domain\Exception\TenantMismatchException;
use App\Administration\Infrastructure\Api\Resource\StudentGuardianResource;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Administration\Infrastructure\Security\StudentGuardianVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProcessorInterface<StudentGuardianResource, StudentGuardianResource>
 */
final readonly class LinkParentToStudentProcessor implements ProcessorInterface
{
    public function __construct(
        private LinkParentToStudentHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

    /**
     * @param StudentGuardianResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): StudentGuardianResource
    {
        if (!$this->authorizationChecker->isGranted(StudentGuardianVoter::MANAGE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à lier un parent à un élève.');
        }

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

        /** @var string $studentId */
        $studentId = $uriVariables['studentId'];
        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        $currentUser = $this->security->getUser();
        $createdBy = $currentUser instanceof SecurityUser ? $currentUser->userId() : null;

        try {
            $command = new LinkParentToStudentCommand(
                studentId: $studentId,
                guardianId: $data->guardianId ?? '',
                relationshipType: $data->relationshipType ?? '',
                tenantId: $tenantId,
                createdBy: $createdBy,
            );

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

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

            return StudentGuardianResource::fromDomain($link);
        } catch (InvalidArgumentException|InvalidGuardianRoleException|InvalidStudentRoleException|TenantMismatchException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (LiaisonDejaExistanteException $e) {
            throw new ConflictHttpException($e->getMessage());
        } catch (MaxGuardiansReachedException $e) {
            throw new UnprocessableEntityHttpException($e->getMessage());
        }
    }
}
