<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\PublishGrades;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Domain\Exception\AucuneNoteSaisieException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Domain\Model\Evaluation\Evaluation;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
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 PublishGradesHandler
{
    public function __construct(
        private EvaluationRepository $evaluationRepository,
        private GradeRepository $gradeRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(PublishGradesCommand $command): Evaluation
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $evaluationId = EvaluationId::fromString($command->evaluationId);
        $teacherId = UserId::fromString($command->teacherId);
        $now = $this->clock->now();

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

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

        if (!$this->gradeRepository->hasGradesForEvaluation($evaluationId, $tenantId)) {
            throw AucuneNoteSaisieException::pourEvaluation($evaluationId);
        }

        $evaluation->publierNotes($now);

        $this->evaluationRepository->save($evaluation);

        return $evaluation;
    }
}
