<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\SubmitHomework;

use App\Administration\Domain\Model\User\UserId;
use App\Scolarite\Application\Port\StudentClassReader;
use App\Scolarite\Domain\Exception\EleveNonAffecteAuDevoirException;
use App\Scolarite\Domain\Exception\RenduNonTrouveException;
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 SubmitHomeworkHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private HomeworkSubmissionRepository $submissionRepository,
        private StudentClassReader $studentClassReader,
        private Clock $clock,
    ) {
    }

    public function __invoke(SubmitHomeworkCommand $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);
        }

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

        if ($submission === null) {
            throw RenduNonTrouveException::pourDevoirEtEleve($homeworkId, $studentId);
        }

        $now = $this->clock->now();
        $submission->soumettre(dueDate: $homework->dueDate, now: $now);

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

        return $submission;
    }
}
