<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UpdateHomework;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\CurrentCalendarProvider;
use App\Scolarite\Application\Port\HtmlSanitizer;
use App\Scolarite\Domain\Exception\NonProprietaireDuDevoirException;
use App\Scolarite\Domain\Model\Homework\Homework;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
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 UpdateHomeworkHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private CurrentCalendarProvider $calendarProvider,
        private DueDateValidator $dueDateValidator,
        private HtmlSanitizer $htmlSanitizer,
        private Clock $clock,
    ) {
    }

    public function __invoke(UpdateHomeworkCommand $command): Homework
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $homeworkId = HomeworkId::fromString($command->homeworkId);
        $now = $this->clock->now();

        $homework = $this->homeworkRepository->get($homeworkId, $tenantId);

        $teacherId = UserId::fromString($command->teacherId);
        if ((string) $homework->teacherId !== (string) $teacherId) {
            throw NonProprietaireDuDevoirException::withId($homeworkId);
        }

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

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

        $homework->modifier(
            title: $command->title,
            description: $description,
            dueDate: $dueDate,
            now: $now,
        );

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

        return $homework;
    }
}
