<?php

declare(strict_types=1);

namespace App\Domain\Manga\Application\EventListener;

use App\Domain\Manga\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Model\Chapter;
use App\Domain\Manga\Domain\Model\ValueObject\ChapterId;
use App\Domain\Manga\Domain\Model\ValueObject\MangaSlug;
use App\Domain\Shared\Domain\Event\VolumeImported;

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

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

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

        foreach ($chapters as $chapter) {
            $updated = new Chapter(
                new ChapterId($chapter->getId()),
                $chapter->getMangaId(),
                $chapter->getNumber(),
                $chapter->getTitle(),
                $chapter->getVolume(),
                $chapter->isVisible(),
                $event->cbzPath,
                $chapter->getCreatedAt(),
            );
            $this->chapterRepository->save($updated);
        }
    }
}


