<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UpdateScheduleSlot;

use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\EnseignantAffectationChecker;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Domain\Model\Schedule\DayOfWeek;
use App\Scolarite\Domain\Model\Schedule\ScheduleSlot;
use App\Scolarite\Domain\Model\Schedule\ScheduleSlotId;
use App\Scolarite\Domain\Model\Schedule\TimeSlot;
use App\Scolarite\Domain\Repository\ScheduleSlotRepository;
use App\Scolarite\Domain\Service\ScheduleConflict;
use App\Scolarite\Domain\Service\ScheduleConflictDetector;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class UpdateScheduleSlotHandler
{
    public function __construct(
        private ScheduleSlotRepository $repository,
        private ScheduleConflictDetector $conflictDetector,
        private EnseignantAffectationChecker $affectationChecker,
        private Clock $clock,
    ) {
    }

    /**
     * @return array{slot: ScheduleSlot, conflicts: array<ScheduleConflict>}
     */
    public function __invoke(UpdateScheduleSlotCommand $command): array
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $slotId = ScheduleSlotId::fromString($command->slotId);

        $slot = $this->repository->get($slotId, $tenantId);

        $classId = ClassId::fromString($command->classId);
        $subjectId = SubjectId::fromString($command->subjectId);
        $teacherId = UserId::fromString($command->teacherId);
        $dayOfWeek = DayOfWeek::from($command->dayOfWeek);
        $newTimeSlot = new TimeSlot($command->startTime, $command->endTime);

        if (!$this->affectationChecker->estAffecte($teacherId, $classId, $subjectId, $tenantId)) {
            throw EnseignantNonAffecteException::pourClasseEtMatiere($teacherId, $classId, $subjectId);
        }

        // Détecte les conflits avant de modifier le slot.
        // On crée un slot temporaire avec les nouvelles valeurs pour la détection.
        $preview = ScheduleSlot::creer(
            tenantId: $tenantId,
            classId: $classId,
            subjectId: $subjectId,
            teacherId: $teacherId,
            dayOfWeek: $dayOfWeek,
            timeSlot: $newTimeSlot,
            room: $command->room,
            isRecurring: $slot->isRecurring,
            now: $this->clock->now(),
        );
        $conflicts = $this->conflictDetector->detectConflicts($preview, $tenantId, $slotId);

        if ($conflicts === [] || $command->forceConflicts) {
            $slot->modifier(
                classId: $classId,
                subjectId: $subjectId,
                teacherId: $teacherId,
                dayOfWeek: $dayOfWeek,
                timeSlot: $newTimeSlot,
                room: $command->room,
                at: $this->clock->now(),
            );
            $this->repository->save($slot);
        }

        return ['slot' => $slot, 'conflicts' => $conflicts];
    }
}
