<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\SendParentInvitation;

use App\Administration\Application\Service\InvitationCodeGenerator;
use App\Administration\Domain\Model\Invitation\ParentInvitation;
use App\Administration\Domain\Model\User\Email;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\ParentInvitationRepository;
use App\Administration\Domain\Repository\UserRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DomainException;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

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

    public function __invoke(SendParentInvitationCommand $command): ParentInvitation
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $studentId = UserId::fromString($command->studentId);
        $parentEmail = new Email($command->parentEmail);
        $createdBy = UserId::fromString($command->createdBy);
        $now = $this->clock->now();

        // Verify student exists and is actually a student
        $student = $this->userRepository->findById($studentId);
        if ($student === null || !$student->aLeRole(Role::ELEVE)) {
            throw new DomainException('L\'élève spécifié n\'existe pas.');
        }

        $code = $this->codeGenerator->generate();

        $invitation = ParentInvitation::creer(
            tenantId: $tenantId,
            studentId: $studentId,
            parentEmail: $parentEmail,
            code: $code,
            createdAt: $now,
            createdBy: $createdBy,
        );

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

        return $invitation;
    }
}
