<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\ConfigureCalendar;

use App\Administration\Application\Port\OfficialCalendarProvider;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendar;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendarRepository;
use App\Administration\Domain\Model\SchoolCalendar\SchoolZone;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

/**
 * Configure le calendrier scolaire en important les données officielles pour une zone.
 */
#[AsMessageHandler(bus: 'command.bus')]
final readonly class ConfigureCalendarHandler
{
    public function __construct(
        private SchoolCalendarRepository $calendarRepository,
        private OfficialCalendarProvider $calendarProvider,
        private Clock $clock,
    ) {
    }

    public function __invoke(ConfigureCalendarCommand $command): SchoolCalendar
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $academicYearId = AcademicYearId::fromString($command->academicYearId);
        $zone = SchoolZone::from($command->zone);

        $calendar = $this->calendarRepository->findByTenantAndYear($tenantId, $academicYearId)
            ?? SchoolCalendar::initialiser($tenantId, $academicYearId);

        $entries = $this->calendarProvider->toutesEntreesOfficielles($zone, $command->academicYear);

        $calendar->configurer($zone, $entries, $this->clock->now());

        $this->calendarRepository->save($calendar);

        return $calendar;
    }
}
