<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\DeleteHomework;

use App\Administration\Domain\Model\User\UserId;
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\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class DeleteHomeworkHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(DeleteHomeworkCommand $command): Homework
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $homeworkId = HomeworkId::fromString($command->homeworkId);

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

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

        $homework->supprimer($this->clock->now());

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

        return $homework;
    }
}
