<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\FetchMangaChapters;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Contract\Service\ChapterSynchronizationServiceInterface;
use App\Domain\Manga\Domain\Exception\MangadexApiException;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;

readonly class FetchMangaChaptersHandler
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository,
        private ChapterSynchronizationServiceInterface $chapterSynchronizationService
    ) {
    }

    public function handle(FetchMangaChapters $command): void
    {
        $manga = $this->mangaRepository->findById($command->mangaId->getValue());

        if ($manga === null) {
            throw new MangaNotFoundException();
        }

        if ($manga->getExternalId() === null) {
            throw new MangadexApiException("Manga has no external_id");
        }

        // Synchronisation initiale (pas d'événements)
        $this->chapterSynchronizationService->synchronizeChapters($manga);
        $this->mangaRepository->save($manga);
    }
}
