<?php

namespace App\Domain\Manga\Application\CommandHandler;

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

readonly class EditMultipleChaptersHandler
{
    public function __construct(
        private ChapterRepositoryInterface $chapterRepository
    ) {}

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

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

            $updatedChapter = $chapter;

            if ($chapterData->title !== null) {
                $updatedChapter = $updatedChapter->updateTitle($chapterData->title);
            }

            if ($chapterData->volume !== null) {
                $updatedChapter = $updatedChapter->updateVolume($chapterData->volume);
            }

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