<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\CreateAppreciationTemplate;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Domain\Exception\CategorieAppreciationInvalideException;
use App\Scolarite\Domain\Model\Grade\AppreciationCategory;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplate;
use App\Scolarite\Domain\Repository\AppreciationTemplateRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

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

    public function __invoke(CreateAppreciationTemplateCommand $command): AppreciationTemplate
    {
        $category = null;
        if ($command->category !== null) {
            $category = AppreciationCategory::tryFrom($command->category);
            if ($category === null) {
                throw CategorieAppreciationInvalideException::pourValeur($command->category);
            }
        }

        $template = AppreciationTemplate::creer(
            tenantId: TenantId::fromString($command->tenantId),
            teacherId: UserId::fromString($command->teacherId),
            title: $command->title,
            content: $command->content,
            category: $category,
            now: $this->clock->now(),
        );

        $this->templateRepository->save($template);

        return $template;
    }
}
