<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\CreateEvaluation;

use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\EnseignantAffectationChecker;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Domain\Model\Evaluation\Coefficient;
use App\Scolarite\Domain\Model\Evaluation\Evaluation;
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 CreateEvaluationHandler
{
    public function __construct(
        private EvaluationRepository $evaluationRepository,
        private EnseignantAffectationChecker $affectationChecker,
        private Clock $clock,
    ) {
    }

    public function __invoke(CreateEvaluationCommand $command): Evaluation
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $classId = ClassId::fromString($command->classId);
        $subjectId = SubjectId::fromString($command->subjectId);
        $teacherId = UserId::fromString($command->teacherId);
        $now = $this->clock->now();

        if (!$this->affectationChecker->estAffecte($teacherId, $classId, $subjectId, $tenantId)) {
            throw EnseignantNonAffecteException::pourClasseEtMatiere($teacherId, $classId, $subjectId);
        }

        $evaluation = Evaluation::creer(
            tenantId: $tenantId,
            classId: $classId,
            subjectId: $subjectId,
            teacherId: $teacherId,
            title: $command->title,
            description: $command->description,
            evaluationDate: new DateTimeImmutable($command->evaluationDate),
            gradeScale: new GradeScale($command->gradeScale),
            coefficient: new Coefficient($command->coefficient),
            now: $now,
        );

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

        return $evaluation;
    }
}
