<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\AccompanyingPeriod\Lifecycle;

use Chill\PersonBundle\Repository\AccompanyingPeriodRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[AsMessageHandler]
class AccompanyingPeriodStepChangeMessageHandler implements MessageHandlerInterface
{
    private const LOG_PREFIX = '[accompanying period step change message handler] ';

    public function __construct(
        private readonly AccompanyingPeriodRepository $accompanyingPeriodRepository,
        private readonly AccompanyingPeriodStepChanger $changer,
    ) {}

    public function __invoke(AccompanyingPeriodStepChangeRequestMessage $message): void
    {
        if (null === $period = $this->accompanyingPeriodRepository->find($message->getPeriodId())) {
            throw new \RuntimeException(self::LOG_PREFIX.'Could not find period with this id: '.$message->getPeriodId());
        }

        ($this->changer)($period, $message->getTransition());
    }
}
