<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UpdateAppreciationTemplate;

use App\Scolarite\Domain\Exception\AppreciationTemplateNonTrouveeException;
use App\Scolarite\Domain\Exception\CategorieAppreciationInvalideException;
use App\Scolarite\Domain\Exception\NonProprietaireDuModeleException;
use App\Scolarite\Domain\Model\Grade\AppreciationCategory;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplate;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplateId;
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 UpdateAppreciationTemplateHandler
{
    public function __construct(
        private AppreciationTemplateRepository $templateRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(UpdateAppreciationTemplateCommand $command): AppreciationTemplate
    {
        $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);
        }

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

        $template->modifier(
            title: $command->title,
            content: $command->content,
            category: $category,
            now: $this->clock->now(),
        );

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

        return $template;
    }
}
