<?php

namespace App\MessageHandler;

use App\Message\RefreshMetadata;
use App\Repository\MangaRepository;
use App\Service\MangadexProvider;
use App\Service\NotificationService;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
readonly class RefreshMetadataHandler
{
    public function __construct(
        private MangaRepository $mangaRepository,
        private MangadexProvider $mangadexProvider,
        private EntityManagerInterface $entityManager,
        private NotificationService $notificationService
    ) {
    }

    public function __invoke(RefreshMetadata $message): void
    {
        $manga = $this->mangaRepository->find($message->getMangaId());
        if (!$manga) {
            return;
        }

        $lastChapters = $this->mangadexProvider->addAllChaptersToManga($manga);

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

            $this->entityManager->persist($manga);
            $this->entityManager->flush();
        } catch (\Exception $e) {
            if ($e instanceof UniqueConstraintViolationException) {
                $this->notificationService->sendUpdate(['status' => 'error', 'message' => 'An error occurred while refreshing ' . $manga->getTitle() . '.']);
                return;
            }
        }

        $this->notificationService->sendUpdate(['status' => 'success', 'message' => $manga->getTitle() . ' refreshed, ' . count($lastChapters) . ' new chapters added.']);
    }
}
