<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\SaveGrades;

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

    /** @return array<Grade> */
    public function __invoke(SaveGradesCommand $command): array
    {
        $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);
        }

        $existingGrades = $this->gradeRepository->findByEvaluation($evaluationId, $tenantId);
        $existingByStudent = [];
        foreach ($existingGrades as $grade) {
            $existingByStudent[(string) $grade->studentId] = $grade;
        }

        $savedGrades = [];

        foreach ($command->grades as $gradeInput) {
            $studentId = UserId::fromString($gradeInput['studentId']);
            $status = GradeStatus::from($gradeInput['status']);
            $value = $gradeInput['value'] !== null ? new GradeValue($gradeInput['value']) : null;

            $existing = $existingByStudent[(string) $studentId] ?? null;

            if ($existing !== null) {
                $existing->modifier(
                    value: $value,
                    status: $status,
                    gradeScale: $evaluation->gradeScale,
                    modifiedBy: $teacherId,
                    now: $now,
                );
                $this->gradeRepository->save($existing);
                $savedGrades[] = $existing;
            } else {
                $grade = Grade::saisir(
                    tenantId: $tenantId,
                    evaluationId: $evaluationId,
                    studentId: $studentId,
                    value: $value,
                    status: $status,
                    gradeScale: $evaluation->gradeScale,
                    createdBy: $teacherId,
                    now: $now,
                );
                $this->gradeRepository->save($grade);
                $savedGrades[] = $grade;
            }
        }

        return $savedGrades;
    }
}
