<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\DeleteChapter;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Shared\Domain\Contract\CommandHandlerInterface;
use App\Domain\Shared\Domain\Contract\CommandInterface;

readonly class DeleteChapterHandler implements CommandHandlerInterface
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository
    ) {
    }

    public function handle(CommandInterface $command): void
    {
        assert($command instanceof DeleteChapter);

        $chapter = $this->mangaRepository->findVisibleChapterById($command->chapterId);

        if (!$chapter) {
            throw new ChapterNotFoundException($command->chapterId);
        }

        $manga = $this->mangaRepository->findById($chapter->getMangaId()->getValue());
        $manga->hideChapter($chapter);
        $this->mangaRepository->save($manga);
    }
}
