<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\CreateManga;
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\Model\Manga;
use App\Domain\Manga\Domain\Model\ValueObject\ExternalId;
use App\Domain\Manga\Domain\Model\ValueObject\ImageUrls;
use App\Domain\Manga\Domain\Model\ValueObject\MangaId;
use App\Domain\Manga\Domain\Model\ValueObject\MangaSlug;
use App\Domain\Manga\Domain\Model\ValueObject\MangaTitle;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Messenger\MessageBusInterface;

readonly class CreateMangaHandler
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository,
        private ImageProcessorInterface $imageProcessor,
        private MessageBusInterface $messageBus
    ) {
    }

    public function handle(CreateManga $command): void
    {
        $manga = new Manga(
            new MangaId(Uuid::uuid4()->toString()),
            new MangaTitle($command->title),
            new MangaSlug($command->slug),
            $command->description,
            $command->author,
            $command->publicationYear,
            $command->genres,
            $command->status,
            $command->externalId ? new ExternalId($command->externalId) : null,
            $command->imageUrl,
            $command->rating,
            null, // imageUrls
            [], // alternativeSlugs
        );

        if (!is_null($command->imageUrl)) {
            try {
                $fullImagePath = $this->imageProcessor->downloadImage($command->imageUrl);
                $thumbnailPath = $this->imageProcessor->createThumbnail($fullImagePath);
                $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);

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