<?php

namespace App\MessageHandler;

use App\Entity\Chapter;
use App\Entity\Manga;
use App\Message\DownloadChapter;
use App\Message\RefreshAndDownloadChapters;
use App\Repository\MangaRepository;
use App\Service\MangadexProvider;
use App\Service\NotificationService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;

#[AsMessageHandler]
final readonly class RefreshAndDownloadChaptersHandler
{
    public function __construct(
        private MangaRepository $mangaRepository,
        private MangadexProvider $mangadexProvider,
        private EntityManagerInterface $entityManager,
        private MessageBusInterface $bus
    ) {

    }

    public function __invoke(RefreshAndDownloadChapters $message): void
    {
        $mangas = $this->mangaRepository->findBy(['monitored' => true]);

        foreach ($mangas as $manga) {
            $chapters = $this->refreshMangas($manga);

            if (empty($chapters)) {
                continue;
            }

            /** @var Chapter $chapter */
            foreach ($chapters as $chapter) {
                $this->bus->dispatch(new DownloadChapter($chapter->getId()));
            }
        }

    }

    private function refreshMangas(Manga $manga): array
    {
        $lastChapters = $this->mangadexProvider->addAllChaptersToManga($manga);

        foreach ($lastChapters as $chapter) {
            $this->entityManager->persist($chapter);
        }

        $this->entityManager->persist($manga);
        $this->entityManager->flush();

        return $lastChapters;
    }
}
