<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\DeleteCbz;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Contract\Service\FileServiceInterface;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;
use App\Domain\Manga\Domain\Exception\CbzFileNotFoundException;
use App\Domain\Shared\Domain\Contract\CommandHandlerInterface;
use App\Domain\Shared\Domain\Contract\CommandInterface;

readonly class DeleteCbzHandler implements CommandHandlerInterface
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository,
        private FileServiceInterface $fileService
    ) {
    }

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

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

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

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

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