<?php

namespace App\Domain\Manga\Application\QueryHandler;

use App\Domain\Manga\Application\Query\SearchManga;
use App\Domain\Manga\Application\Response\MangaSearchItem;
use App\Domain\Manga\Application\Response\MangaSearchResponse;
use App\Domain\Manga\Domain\Contract\Provider\MangaProviderInterface;
use App\Domain\Manga\Domain\Model\Manga;

readonly class SearchMangaHandler
{
    public function __construct(
        private MangaProviderInterface $mangaProvider
    ) {
    }

    public function handle(SearchManga $query): MangaSearchResponse
    {
        $mangaCollection = $this->mangaProvider->search($query->title);


        return new MangaSearchResponse(
            array_map(
                fn (Manga $manga, int $index) => new MangaSearchItem(
                    id: $index,
                    externalId: $manga->getExternalId()->getValue(),
                    title: $manga->getTitle()->getValue(),
                    slug: $manga->getSlug()->getValue(),
                    description: $manga->getDescription(),
                    author: $manga->getAuthor(),
                    publicationYear: $manga->getPublicationYear(),
                    genres: $manga->getGenres(),
                    status: $manga->getStatus(),
                    imageUrl: $manga->getImageUrl(),
                    thumbnailUrl: $manga->getImageUrls()?->getThumbnail(),
                    rating: $manga->getRating()
                ),
                $mangaCollection->getItems(),
                array_keys($mangaCollection->getItems())
            )
        );
    }
}
