<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetStudentsForParent\GetStudentsForParentHandler;
use App\Administration\Application\Query\GetStudentsForParent\GetStudentsForParentQuery;
use App\Administration\Infrastructure\Api\Resource\MyChildrenResource;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * State Provider pour récupérer les enfants du parent connecté.
 *
 * @implements ProviderInterface<MyChildrenResource>
 */
final readonly class MyChildrenProvider implements ProviderInterface
{
    public function __construct(
        private GetStudentsForParentHandler $handler,
        private Security $security,
        private TenantContext $tenantContext,
    ) {
    }

    /**
     * @return MyChildrenResource[]
     */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $currentUser = $this->security->getUser();
        if (!$currentUser instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

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

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

        $dtos = ($this->handler)(new GetStudentsForParentQuery(
            guardianId: $currentUser->userId(),
            tenantId: $tenantId,
        ));

        return array_map(MyChildrenResource::fromDto(...), $dtos);
    }
}
