<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
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\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer une liaison parent-élève individuelle.
 *
 * @implements ProviderInterface<StudentGuardianResource>
 */
final readonly class GuardianItemProvider implements ProviderInterface
{
    public function __construct(
        private StudentGuardianRepository $repository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?StudentGuardianResource
    {
        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string $studentId */
        $studentId = $uriVariables['studentId'];

        if (!$this->authorizationChecker->isGranted(StudentGuardianVoter::VIEW_STUDENT, $studentId)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir les parents de cet élève.');
        }

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

        try {
            $link = $this->repository->findByStudentAndGuardian(
                UserId::fromString($studentId),
                UserId::fromString($guardianId),
                TenantId::fromString($tenantId),
            );
        } catch (InvalidArgumentException) {
            return null;
        }

        if ($link === null) {
            return null;
        }

        return StudentGuardianResource::fromDomain($link);
    }
}
