<?php

namespace App\Domain\Scraping\Infrastructure\EventListener;

use App\Domain\Manga\Domain\Event\ChapterReadyForScraping;
use App\Domain\Scraping\Application\Command\ScrapeChapter;
use App\Domain\Scraping\Application\CommandHandler\ScrapeChapterHandler;
use App\Domain\Scraping\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Scraping\Domain\Contract\Repository\MangaRepositoryInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

class AutoScrapingListener
{
    public function __construct(
        private readonly ScrapeChapterHandler $scrapeChapterHandler,
        private readonly ChapterRepositoryInterface $chapterRepository,
        private readonly MangaRepositoryInterface $mangaRepository,
    ) {
    }

    #[AsMessageHandler]
    public function onChapterReadyForScraping(ChapterReadyForScraping $event): void
    {
        $chapter = $this->chapterRepository->getById($event->chapterId->getValue());
        $manga = $this->mangaRepository->getById($chapter->mangaId);

        if ($manga->isMonitored()) {
            $this->scrapeChapterHandler->handle(new ScrapeChapter($event->chapterId->getValue()));
        }
    }
}
