<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetParentsForStudent\GetParentsForStudentHandler;
use App\Administration\Application\Query\GetParentsForStudent\GetParentsForStudentQuery;
use App\Administration\Application\Query\GetParentsForStudent\GuardianForStudentDto;
use App\Administration\Infrastructure\Api\Resource\StudentGuardianResource;
use App\Administration\Infrastructure\Security\StudentGuardianVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

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 les parents/tuteurs d'un élève.
 *
 * @implements ProviderInterface<StudentGuardianResource>
 */
final readonly class GuardiansForStudentProvider implements ProviderInterface
{
    public function __construct(
        private GetParentsForStudentHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @return StudentGuardianResource[]
     */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        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.');
        }
        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        $dtos = ($this->handler)(new GetParentsForStudentQuery(
            studentId: $studentId,
            tenantId: $tenantId,
        ));

        return array_map(static function (GuardianForStudentDto $dto) use ($studentId): StudentGuardianResource {
            $resource = StudentGuardianResource::fromDto($dto);
            $resource->studentId = $studentId;

            return $resource;
        }, $dtos);
    }
}
