<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\EditManga;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Model\ValueObject\MangaTitle;

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

    public function handle(EditManga $command): void
    {
        $manga = $this->mangaRepository->findById($command->id);

        if (!$manga) {
            throw new MangaNotFoundException($command->id);
        }

        // Update only provided fields (partial update)
        if (null !== $command->title) {
            $manga->updateTitle(new MangaTitle($command->title));
        }

        if (null !== $command->description) {
            $manga->updateDescription($command->description);
        }

        if (null !== $command->author) {
            $manga->updateAuthor($command->author);
        }

        if (null !== $command->publicationYear) {
            $manga->updatePublicationYear($command->publicationYear);
        }

        if (null !== $command->genres) {
            $manga->updateGenres($command->genres);
        }

        if (null !== $command->status) {
            $manga->updateStatus($command->status);
        }

        if (null !== $command->rating) {
            $manga->setRating($command->rating);
        }

        if (null !== $command->alternativeSlugs) {
            $manga->updateAlternativeSlugs($command->alternativeSlugs);
        }

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