<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Service;

use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendar;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendarRepository;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Scolarite\Application\Port\CurrentCalendarProvider;
use App\Shared\Domain\Tenant\TenantId;
use Override;
use RuntimeException;

/**
 * Fournit le calendrier scolaire de l'année courante.
 */
final readonly class CurrentYearCalendarProvider implements CurrentCalendarProvider
{
    public function __construct(
        private SchoolCalendarRepository $calendarRepository,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    #[Override]
    public function forCurrentYear(TenantId $tenantId): SchoolCalendar
    {
        $academicYearId = $this->academicYearResolver->resolve('current');

        if ($academicYearId === null) {
            throw new RuntimeException(
                'Aucune année scolaire configurée pour le tenant ' . $tenantId . '. '
                . 'Veuillez configurer une année scolaire avant de consulter l\'emploi du temps.',
            );
        }

        $yearId = AcademicYearId::fromString($academicYearId);

        return $this->calendarRepository->findByTenantAndYear($tenantId, $yearId)
            ?? SchoolCalendar::initialiser($tenantId, $yearId);
    }
}
