<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\SaveDraftSubmission;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\HtmlSanitizer;
use App\Scolarite\Application\Port\StudentClassReader;
use App\Scolarite\Domain\Exception\EleveNonAffecteAuDevoirException;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Model\HomeworkSubmission\HomeworkSubmission;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Scolarite\Domain\Repository\HomeworkSubmissionRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class SaveDraftSubmissionHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private HomeworkSubmissionRepository $submissionRepository,
        private StudentClassReader $studentClassReader,
        private HtmlSanitizer $htmlSanitizer,
        private Clock $clock,
    ) {
    }

    public function __invoke(SaveDraftSubmissionCommand $command): HomeworkSubmission
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $homeworkId = HomeworkId::fromString($command->homeworkId);
        $studentId = UserId::fromString($command->studentId);

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

        $classId = $this->studentClassReader->currentClassId($command->studentId, $tenantId);

        if ($classId === null || $classId !== (string) $homework->classId) {
            throw EleveNonAffecteAuDevoirException::pourEleve($studentId, $homeworkId);
        }

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

        $now = $this->clock->now();

        $existing = $this->submissionRepository->findByHomeworkAndStudent($homeworkId, $studentId, $tenantId);

        if ($existing !== null) {
            $existing->modifierBrouillon($sanitizedHtml, $now);
            $this->submissionRepository->save($existing);

            return $existing;
        }

        $submission = HomeworkSubmission::creerBrouillon(
            tenantId: $tenantId,
            homeworkId: $homeworkId,
            studentId: $studentId,
            responseHtml: $sanitizedHtml,
            now: $now,
        );

        $this->submissionRepository->save($submission);

        return $submission;
    }
}
