<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\EditMultipleChapters;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\ChapterNotFoundException;

readonly class EditMultipleChaptersHandler
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository
    ) {
    }

    public function handle(EditMultipleChapters $command): void
    {
        foreach ($command->chapters as $chapterData) {
            $chapter = $this->mangaRepository->findChapterById($chapterData->id);

            if (!$chapter) {
                throw new ChapterNotFoundException($chapterData->id);
            }

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

            if ($chapterData->title !== null) {
                $manga->updateChapterTitle($chapter, $chapterData->title);
            }

            if ($chapterData->volume !== null) {
                $manga->updateChapterVolume($chapter, $chapterData->volume);
            }

            $this->mangaRepository->save($manga);
        }
    }
}
