<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Service;

use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\ClassAssignmentRepository;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Scolarite\Application\Port\StudentClassReader;
use App\Shared\Domain\Tenant\TenantId;
use Override;

/**
 * Résout la classe d'un élève pour l'année scolaire courante.
 */
final readonly class CurrentYearStudentClassReader implements StudentClassReader
{
    public function __construct(
        private ClassAssignmentRepository $classAssignmentRepository,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    #[Override]
    public function currentClassId(string $studentId, TenantId $tenantId): ?string
    {
        $academicYearId = $this->academicYearResolver->resolve('current');

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

        $assignment = $this->classAssignmentRepository->findByStudent(
            UserId::fromString($studentId),
            AcademicYearId::fromString($academicYearId),
            $tenantId,
        );

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

        return (string) $assignment->classId;
    }
}
