<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\CreateScheduleSlot;

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\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 CreateScheduleSlotHandler
{
    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(CreateScheduleSlotCommand $command): array
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $classId = ClassId::fromString($command->classId);
        $subjectId = SubjectId::fromString($command->subjectId);
        $teacherId = UserId::fromString($command->teacherId);
        $timeSlot = new TimeSlot($command->startTime, $command->endTime);

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

        $slot = ScheduleSlot::creer(
            tenantId: $tenantId,
            classId: $classId,
            subjectId: $subjectId,
            teacherId: $teacherId,
            dayOfWeek: DayOfWeek::from($command->dayOfWeek),
            timeSlot: $timeSlot,
            room: $command->room,
            isRecurring: $command->isRecurring,
            now: $this->clock->now(),
        );

        $conflicts = $this->conflictDetector->detectConflicts($slot, $tenantId);

        if ($conflicts === [] || $command->forceConflicts) {
            $this->repository->save($slot);
        }

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