<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UnlinkParentFromStudent\UnlinkParentFromStudentCommand;
use App\Administration\Application\Command\UnlinkParentFromStudent\UnlinkParentFromStudentHandler;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\StudentGuardianRepository;
use App\Administration\Infrastructure\Api\Resource\StudentGuardianResource;
use App\Administration\Infrastructure\Security\StudentGuardianVoter;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
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<StudentGuardianResource, null>
 */
final readonly class UnlinkParentFromStudentProcessor implements ProcessorInterface
{
    public function __construct(
        private UnlinkParentFromStudentHandler $handler,
        private StudentGuardianRepository $repository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private MessageBusInterface $eventBus,
    ) {
    }

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

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

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

        try {
            $existingLink = $this->repository->findByStudentAndGuardian(
                UserId::fromString($studentId),
                UserId::fromString($guardianId),
                TenantId::fromString($tenantId),
            );
        } catch (InvalidArgumentException) {
            throw new NotFoundHttpException('Liaison parent-élève introuvable.');
        }

        if ($existingLink === null) {
            throw new NotFoundHttpException('Liaison parent-élève introuvable.');
        }

        $link = ($this->handler)(new UnlinkParentFromStudentCommand(
            linkId: (string) $existingLink->id,
            tenantId: $tenantId,
        ));

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

        return null;
    }
}
