<?php

declare(strict_types=1);

namespace App\Domain\Manga\Application\EventListener;

use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Shared\Domain\Event\ChapterScraped;

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

    public function __invoke(ChapterScraped $event): void
    {
        $chapter = $this->mangaRepository->findChapterById($event->chapterId);
        if (!$chapter) {
            return;
        }

        $manga = $this->mangaRepository->findById($chapter->getMangaId()->getValue());
        if (!$manga) {
            return;
        }

        $manga->updateChapterPages($chapter, $event->pagesDirectory, $event->pageCount);
        $this->mangaRepository->save($manga);
    }
}
