<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\DeleteChapter;
use App\Domain\Manga\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Manga\Domain\Model\Chapter;
use App\Domain\Manga\Domain\Model\ValueObject\ChapterId;
use App\Domain\Shared\Domain\Contract\CommandHandlerInterface;
use App\Domain\Shared\Domain\Contract\CommandInterface;

readonly class DeleteChapterHandler implements CommandHandlerInterface
{
    public function __construct(
        private ChapterRepositoryInterface $chapterRepository
    ) {}

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

        $chapter = $this->chapterRepository->findVisibleById($command->chapterId);

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

        $updatedChapter = new Chapter(
            id: new ChapterId($chapter->getId()),
            mangaId: $chapter->getMangaId(),
            number: $chapter->getNumber(),
            title: $chapter->getTitle(),
            volume: $chapter->getVolume(),
            isVisible: false,
            cbzPath: $chapter->getCbzPath(),
            createdAt: $chapter->getCreatedAt()
        );

        $this->chapterRepository->save($updatedChapter);
    }
}
