<?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\VolumeImported;

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

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

        $chapters = $this->mangaRepository->findChaptersByMangaIdAndVolume($manga->getId()->getValue(), (int) $event->volume);
        if ($chapters === []) {
            return;
        }

        foreach ($chapters as $chapter) {
            $manga->updateChapterPages($chapter, $event->cbzPath, $chapter->getPageCount());
        }
        $this->mangaRepository->save($manga);
    }
}
