<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\UpdateClass;

use App\Administration\Domain\Exception\ClasseDejaExistanteException;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\SchoolClass\ClassName;
use App\Administration\Domain\Model\SchoolClass\SchoolClass;
use App\Administration\Domain\Model\SchoolClass\SchoolLevel;
use App\Administration\Domain\Repository\ClassRepository;
use App\Shared\Domain\Clock;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

/**
 * Handler pour modifier une classe scolaire existante.
 */
#[AsMessageHandler(bus: 'command.bus')]
final readonly class UpdateClassHandler
{
    public function __construct(
        private ClassRepository $classRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(UpdateClassCommand $command): SchoolClass
    {
        $class = $this->classRepository->get(ClassId::fromString($command->classId));
        $now = $this->clock->now();

        if ($command->name !== null) {
            $newName = new ClassName($command->name);

            // Vérifier l'unicité du nouveau nom (sauf si c'est le même)
            if (!$class->name->equals($newName)) {
                $existingClass = $this->classRepository->findByName(
                    $newName,
                    $class->tenantId,
                    $class->academicYearId,
                );

                if ($existingClass !== null && !$existingClass->id->equals($class->id)) {
                    throw ClasseDejaExistanteException::avecNom($newName);
                }
            }

            $class->renommer($newName, $now);
        }

        if ($command->level !== null) {
            $class->changerNiveau(SchoolLevel::from($command->level), $now);
        } elseif ($command->clearLevel) {
            $class->changerNiveau(null, $now);
        }

        if ($command->capacity !== null) {
            $class->changerCapacite($command->capacity, $now);
        } elseif ($command->clearCapacity) {
            $class->changerCapacite(null, $now);
        }

        if ($command->description !== null) {
            $class->decrire($command->description, $now);
        } elseif ($command->clearDescription) {
            $class->decrire(null, $now);
        }

        $this->classRepository->save($class);

        return $class;
    }
}
