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

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

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

        $chapters = $this->chapterRepository->findVisibleByMangaIdAndVolume($manga->getId()->getValue(), (int) $event->volume);
        foreach ($chapters as $chapter) {
            if ($chapter->getNumber() === (float) $event->chapterNumber) {
                $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);
                break;
            }
        }
    }
}


