<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\SaveAppreciation;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Domain\Model\Grade\Grade;
use App\Scolarite\Domain\Model\Grade\GradeId;
use App\Scolarite\Domain\Repository\EvaluationRepository;
use App\Scolarite\Domain\Repository\GradeRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class SaveAppreciationHandler
{
    public function __construct(
        private EvaluationRepository $evaluationRepository,
        private GradeRepository $gradeRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(SaveAppreciationCommand $command): Grade
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $gradeId = GradeId::fromString($command->gradeId);
        $teacherId = UserId::fromString($command->teacherId);

        $grade = $this->gradeRepository->get($gradeId, $tenantId);

        $evaluation = $this->evaluationRepository->get($grade->evaluationId, $tenantId);

        if ((string) $evaluation->teacherId !== (string) $teacherId) {
            throw NonProprietaireDeLEvaluationException::withId($grade->evaluationId);
        }

        $grade->saisirAppreciation($command->appreciation, $this->clock->now());
        $this->gradeRepository->saveAppreciation($grade);

        return $grade;
    }
}
