<?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 ($command->title !== null) {
            $manga->updateTitle(new MangaTitle($command->title));
        }

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

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

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

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

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

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

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

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