<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\DeleteEvaluation;

use App\Administration\Domain\Model\User\UserId;
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\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

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

    public function __invoke(DeleteEvaluationCommand $command): Evaluation
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $evaluationId = EvaluationId::fromString($command->evaluationId);

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

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

        $evaluation->supprimer($this->clock->now());

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

        return $evaluation;
    }
}
