<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetPeriods;

use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Repository\PeriodConfigurationRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;

use function array_map;

use Symfony\Component\Messenger\Attribute\AsMessageHandler;

/**
 * Handler pour récupérer la configuration des périodes d'une année scolaire.
 */
#[AsMessageHandler(bus: 'query.bus')]
final readonly class GetPeriodsHandler
{
    public function __construct(
        private PeriodConfigurationRepository $repository,
        private Clock $clock,
    ) {
    }

    public function __invoke(GetPeriodsQuery $query): ?PeriodsResultDto
    {
        $config = $this->repository->findByAcademicYear(
            TenantId::fromString($query->tenantId),
            AcademicYearId::fromString($query->academicYearId),
        );

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

        $now = $this->clock->now();
        $currentPeriod = $config->currentPeriod($now);

        $periodDtos = array_map(
            static fn ($period) => PeriodDto::fromDomain($period, $now),
            $config->periods,
        );

        $currentPeriodDto = $currentPeriod !== null
            ? PeriodDto::fromDomain($currentPeriod, $now)
            : null;

        return new PeriodsResultDto(
            type: $config->type->value,
            periods: $periodDtos,
            currentPeriod: $currentPeriodDto,
        );
    }
}
