<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\CreateHomework;

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\CurrentCalendarProvider;
use App\Scolarite\Application\Port\EnseignantAffectationChecker;
use App\Scolarite\Application\Port\HomeworkRulesChecker;
use App\Scolarite\Application\Port\HtmlSanitizer;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Domain\Exception\ReglesDevoirsNonRespecteesException;
use App\Scolarite\Domain\Model\Homework\Homework;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Scolarite\Domain\Service\DueDateValidator;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use DateTimeImmutable;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class CreateHomeworkHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private EnseignantAffectationChecker $affectationChecker,
        private CurrentCalendarProvider $calendarProvider,
        private DueDateValidator $dueDateValidator,
        private HomeworkRulesChecker $rulesChecker,
        private HtmlSanitizer $htmlSanitizer,
        private Clock $clock,
    ) {
    }

    public function __invoke(CreateHomeworkCommand $command): Homework
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $classId = ClassId::fromString($command->classId);
        $subjectId = SubjectId::fromString($command->subjectId);
        $teacherId = UserId::fromString($command->teacherId);
        $now = $this->clock->now();

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

        $calendar = $this->calendarProvider->forCurrentYear($tenantId);
        $dueDate = new DateTimeImmutable($command->dueDate);
        $this->dueDateValidator->valider($dueDate, $now, $calendar);

        $rulesResult = $this->rulesChecker->verifier($tenantId, $dueDate, $now);

        if ($rulesResult->estBloquant()) {
            throw new ReglesDevoirsNonRespecteesException(
                $rulesResult->toArray(),
                bloquant: true,
                suggestedDates: $rulesResult->suggestedDates,
            );
        }

        if ($rulesResult->estAvertissement() && !$command->acknowledgeWarning) {
            throw new ReglesDevoirsNonRespecteesException($rulesResult->toArray());
        }

        $description = $command->description !== null
            ? $this->htmlSanitizer->sanitize($command->description)
            : null;

        $homework = Homework::creer(
            tenantId: $tenantId,
            classId: $classId,
            subjectId: $subjectId,
            teacherId: $teacherId,
            title: $command->title,
            description: $description,
            dueDate: $dueDate,
            now: $now,
        );

        if ($command->acknowledgeWarning && $rulesResult->estAvertissement()) {
            $homework->acknowledgeRuleWarning($rulesResult->ruleTypes(), $now);
        }

        $this->homeworkRepository->save($homework);

        return $homework;
    }
}
