<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\DeleteAppreciationTemplate;

use App\Scolarite\Domain\Exception\AppreciationTemplateNonTrouveeException;
use App\Scolarite\Domain\Exception\NonProprietaireDuModeleException;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplateId;
use App\Scolarite\Domain\Repository\AppreciationTemplateRepository;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class DeleteAppreciationTemplateHandler
{
    public function __construct(
        private AppreciationTemplateRepository $templateRepository,
    ) {
    }

    public function __invoke(DeleteAppreciationTemplateCommand $command): void
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $templateId = AppreciationTemplateId::fromString($command->templateId);

        $template = $this->templateRepository->findById($templateId, $tenantId);

        if ($template === null) {
            throw AppreciationTemplateNonTrouveeException::withId($templateId);
        }

        if ((string) $template->teacherId !== $command->teacherId) {
            throw NonProprietaireDuModeleException::withId($templateId);
        }

        $this->templateRepository->delete($templateId, $tenantId);
    }
}
