<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\CreateMangaFromMangadex;
use App\Domain\Manga\Application\Response\CreateMangaResponse;
use App\Domain\Manga\Domain\Contract\Provider\MangaProviderInterface;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Contract\Service\ImageProcessorInterface;
use App\Domain\Manga\Domain\Event\MangaCreated;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Model\ValueObject\ExternalId;
use App\Domain\Manga\Domain\Model\ValueObject\ImageUrls;
use App\Domain\Shared\Domain\Contract\EventDispatcherInterface;

readonly class CreateMangaFromMangadexHandler
{
    public function __construct(
        private MangaProviderInterface $mangaProvider,
        private MangaRepositoryInterface $mangaRepository,
        private ImageProcessorInterface $imageProcessor,
        private EventDispatcherInterface $eventDispatcher
    ) {
    }

    public function handle(CreateMangaFromMangadex $command): void
    {
        $manga = $this->mangaProvider->findByExternalId(new ExternalId($command->externalId));

        if ($manga === null) {
            throw new MangaNotFoundException('Manga not found on Mangadex');
        }

        try {
            // Télécharge l'image originale
            $fullImagePath = $this->imageProcessor->downloadImage($manga->getImageUrl());

            // Crée la miniature à partir de l'image originale
            $thumbnailPath = $this->imageProcessor->createThumbnail($fullImagePath);

            // Met à jour le manga avec les nouveaux chemins d'images
            $manga->updateImageUrls(new ImageUrls($fullImagePath, $thumbnailPath));
        } catch (\Exception $e) {
            throw new \RuntimeException('Erreur lors du traitement de l\'image : ' . $e->getMessage());
        }

        $this->mangaRepository->save($manga);

        $this->eventDispatcher->dispatch(new MangaCreated($manga->getId()->getValue(), $command->externalId));
    }
}
