<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\ResendParentInvitation;

use App\Administration\Application\Service\InvitationCodeGenerator;
use App\Administration\Domain\Model\Invitation\ParentInvitation;
use App\Administration\Domain\Model\Invitation\ParentInvitationId;
use App\Administration\Domain\Repository\ParentInvitationRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class ResendParentInvitationHandler
{
    public function __construct(
        private ParentInvitationRepository $invitationRepository,
        private InvitationCodeGenerator $codeGenerator,
        private Clock $clock,
    ) {
    }

    public function __invoke(ResendParentInvitationCommand $command): ParentInvitation
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $invitationId = ParentInvitationId::fromString($command->invitationId);

        $invitation = $this->invitationRepository->get($invitationId, $tenantId);

        $newCode = $this->codeGenerator->generate();
        $invitation->renvoyer($newCode, $this->clock->now());

        $this->invitationRepository->save($invitation);

        return $invitation;
    }
}
