<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\EventHandler;

use App\Scolarite\Application\Port\PeriodFinder;
use App\Scolarite\Application\Service\RecalculerMoyennesService;
use App\Scolarite\Domain\Event\NoteModifiee;
use App\Scolarite\Domain\Event\NoteSaisie;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
use App\Scolarite\Domain\Repository\EvaluationRepository;
use App\Scolarite\Domain\Repository\GradeRepository;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'event.bus')]
final readonly class RecalculerMoyennesOnNoteModifieeHandler
{
    public function __construct(
        private TenantContext $tenantContext,
        private EvaluationRepository $evaluationRepository,
        private GradeRepository $gradeRepository,
        private PeriodFinder $periodFinder,
        private RecalculerMoyennesService $service,
    ) {
    }

    public function __invoke(NoteSaisie|NoteModifiee $event): void
    {
        $tenantId = $this->tenantContext->getCurrentTenantId();
        $evaluationId = EvaluationId::fromString($event->evaluationId);

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

        if ($evaluation === null || !$evaluation->notesPubliees()) {
            return;
        }

        $this->service->recalculerStatistiquesEvaluation($evaluationId, $tenantId);

        $gradeId = $event instanceof NoteSaisie ? $event->gradeId : $event->gradeId;
        $grade = $this->gradeRepository->findById($gradeId, $tenantId);

        if ($grade === null) {
            return;
        }

        $period = $this->periodFinder->findForDate($evaluation->evaluationDate, $tenantId);

        if ($period === null) {
            return;
        }

        $this->service->recalculerMoyenneEleve(
            $grade->studentId,
            $evaluation->subjectId,
            $evaluation->classId,
            $period,
            $tenantId,
        );
    }
}
