<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\TruncateSlotRecurrence;

use App\Scolarite\Domain\Exception\DateExceptionInvalideException;
use App\Scolarite\Domain\Model\Schedule\ScheduleSlotId;
use App\Scolarite\Domain\Repository\ScheduleSlotRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;

final readonly class TruncateSlotRecurrenceHandler
{
    public function __construct(
        private ScheduleSlotRepository $slotRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(TruncateSlotRecurrenceCommand $command): void
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $slotId = ScheduleSlotId::fromString($command->slotId);
        $slot = $this->slotRepository->get($slotId, $tenantId);
        $fromDate = new DateTimeImmutable($command->fromDate);

        if (!$slot->isActiveOnDate($fromDate)) {
            throw DateExceptionInvalideException::pourSlotEtDate($slotId, $fromDate);
        }

        $now = $this->clock->now();
        $dayBefore = $fromDate->modify('-1 day');
        $slot->terminerRecurrenceLe($dayBefore, $now);
        $this->slotRepository->save($slot);
    }
}
