<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\AssignTeacher;

use App\Administration\Domain\Exception\AffectationDejaExistanteException;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\TeacherAssignment\TeacherAssignment;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\ClassRepository;
use App\Administration\Domain\Repository\SubjectRepository;
use App\Administration\Domain\Repository\TeacherAssignmentRepository;
use App\Administration\Domain\Repository\UserRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class AssignTeacherHandler
{
    public function __construct(
        private TeacherAssignmentRepository $assignmentRepository,
        private UserRepository $userRepository,
        private ClassRepository $classRepository,
        private SubjectRepository $subjectRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(AssignTeacherCommand $command): TeacherAssignment
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $teacherId = UserId::fromString($command->teacherId);
        $classId = ClassId::fromString($command->classId);
        $subjectId = SubjectId::fromString($command->subjectId);
        $academicYearId = AcademicYearId::fromString($command->academicYearId);

        // Valider l'existence des entités référencées (throws NotFoundException)
        $this->userRepository->get($teacherId);
        $this->classRepository->get($classId);
        $this->subjectRepository->get($subjectId);

        // Vérifier l'unicité du triplet enseignant × classe × matière
        $existing = $this->assignmentRepository->findByTeacherClassSubject(
            $teacherId,
            $classId,
            $subjectId,
            $academicYearId,
            $tenantId,
        );

        if ($existing !== null) {
            throw AffectationDejaExistanteException::pourTriple($teacherId, $classId, $subjectId);
        }

        // Vérifier si une affectation retirée existe pour ce même triplet.
        // Si oui, la réactiver au lieu d'en créer une nouvelle (évite la violation
        // de la contrainte UNIQUE qui couvre tous les statuts).
        $removed = $this->assignmentRepository->findRemovedByTeacherClassSubject(
            $teacherId,
            $classId,
            $subjectId,
            $academicYearId,
            $tenantId,
        );

        if ($removed !== null) {
            $removed->reactiver($this->clock->now());
            $this->assignmentRepository->save($removed);

            return $removed;
        }

        $assignment = TeacherAssignment::creer(
            tenantId: $tenantId,
            teacherId: $teacherId,
            classId: $classId,
            subjectId: $subjectId,
            academicYearId: $academicYearId,
            createdAt: $this->clock->now(),
        );

        $this->assignmentRepository->save($assignment);

        return $assignment;
    }
}
