<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UpdateEvaluation;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\EvaluationGradesChecker;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Domain\Model\Evaluation\Coefficient;
use App\Scolarite\Domain\Model\Evaluation\Evaluation;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
use App\Scolarite\Domain\Model\Evaluation\GradeScale;
use App\Scolarite\Domain\Repository\EvaluationRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

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

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

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

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

        $hasGrades = $this->gradesChecker->hasGrades($evaluationId, $tenantId);

        $evaluation->modifier(
            title: $command->title,
            description: $command->description,
            coefficient: new Coefficient($command->coefficient),
            evaluationDate: new DateTimeImmutable($command->evaluationDate),
            gradeScale: $command->gradeScale !== null ? new GradeScale($command->gradeScale) : null,
            hasGrades: $hasGrades,
            now: $now,
        );

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

        return $evaluation;
    }
}
