<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\RefreshMangaChapters;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Contract\Service\ChapterSynchronizationServiceInterface;
use App\Domain\Manga\Domain\Event\ChapterReadyForScraping;
use App\Domain\Manga\Domain\Model\ValueObject\ChapterId;
use DateTimeImmutable;
use Symfony\Component\Messenger\MessageBusInterface;

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

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

        if ($manga === null) {
            throw new \RuntimeException('Manga not found');
        }

        // Synchronisation + récupération des nouveaux IDs
        $newChapterIds = $this->chapterSynchronizationService->synchronizeChapters($manga);

        // Mise à jour de la date de monitoring
        $manga->updateLastMonitoringCheck(new DateTimeImmutable());
        $this->mangaRepository->save($manga);

        // Événement de scraping pour chaque nouveau chapitre
        foreach ($newChapterIds as $chapterId) {
            $this->eventBus->dispatch(
                new ChapterReadyForScraping(new ChapterId($chapterId))
            );
        }
    }
}
