<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\DeleteCbz;
use App\Domain\Manga\Domain\Contract\Repository\ChapterRepositoryInterface;
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\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 DeleteCbzHandler implements CommandHandlerInterface
{
    public function __construct(
        private ChapterRepositoryInterface $chapterRepository,
        private FileServiceInterface $fileService
    ) {}

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

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

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

        // Check if chapter has a CBZ file
        if (!$chapter->isAvailable()) {
            throw new CbzFileNotFoundException($command->chapterId);
        }

        // Delete the physical CBZ file
        // Note: We'll need to get the CBZ path from somewhere, likely from a legacy repository
        // For now, we'll just mark the chapter as not available

        // Update chapter to mark CBZ as not available
        $updatedChapter = new Chapter(
            new ChapterId($chapter->getId()),
            $chapter->getMangaId(),
            $chapter->getNumber(),
            $chapter->getTitle(),
            $chapter->getVolume(),
            $chapter->isVisible(),
            null,
            $chapter->getCreatedAt()
        );

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