<?php

declare(strict_types=1);

namespace App\Domain\Manga\Application\EventListener;

use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Model\ValueObject\MangaSlug;
use App\Domain\Shared\Domain\Event\ChapterImported;

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

    public function __invoke(ChapterImported $event): void
    {
        $manga = $this->mangaRepository->findBySlug(new MangaSlug($event->mangaSlug));
        if (!$manga) {
            return;
        }

        $chapters = $this->mangaRepository->findVisibleChaptersByMangaIdAndVolume($manga->getId()->getValue(), (int) $event->volume);
        foreach ($chapters as $chapter) {
            if ($chapter->getNumber() === (float) $event->chapterNumber) {
                $manga->updateChapterPages($chapter, $event->cbzPath, $chapter->getPageCount());
                $this->mangaRepository->save($manga);
                break;
            }
        }
    }
}
