<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetStudentsForParent;

use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\StudentGuardianRepository;
use App\Administration\Domain\Repository\UserRepository;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

/**
 * Handler pour récupérer les élèves liés à un parent.
 */
#[AsMessageHandler(bus: 'query.bus')]
final readonly class GetStudentsForParentHandler
{
    public function __construct(
        private StudentGuardianRepository $repository,
        private UserRepository $userRepository,
    ) {
    }

    /**
     * @return StudentForParentDto[]
     */
    public function __invoke(GetStudentsForParentQuery $query): array
    {
        $links = $this->repository->findStudentsForGuardian(
            UserId::fromString($query->guardianId),
            TenantId::fromString($query->tenantId),
        );

        return array_map(
            fn ($link) => StudentForParentDto::fromDomainWithUser(
                $link,
                $this->userRepository->get($link->studentId),
            ),
            $links,
        );
    }
}
