<?php

namespace App\Domain\Manga\Application\QueryHandler;

use App\Domain\Manga\Application\Query\SearchLocalManga;
use App\Domain\Manga\Application\Response\MangaListResponse;
use App\Domain\Manga\Application\Response\MangaResponse;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Model\Manga;

readonly class SearchLocalMangaHandler
{
    public function __construct(
        private MangaRepositoryInterface $repository
    ) {
    }

    public function handle(SearchLocalManga $query): MangaListResponse
    {
        $mangas = $this->repository->search($query->query, $query->page, $query->limit);
        $total = $this->repository->countSearch($query->query);

        return new MangaListResponse(
            mangas: array_map(
                fn (Manga $manga) => new MangaResponse(
                    id: $manga->getId()->getValue(),
                    title: $manga->getTitle()->getValue(),
                    slug: $manga->getSlug()->getValue(),
                    alternativeSlugs: $manga->getAlternativeSlugs(),
                    description: $manga->getDescription(),
                    author: $manga->getAuthor(),
                    publicationYear: $manga->getPublicationYear(),
                    genres: $manga->getGenres(),
                    status: $manga->getStatus(),
                    externalId: $manga->getExternalId()?->getValue() ?? '',
                    imageUrl: $manga->getImageUrls()->getFull(),
                    thumbnailUrl: $manga->getImageUrls()->getThumbnail(),
                    rating: $manga->getRating(),
                    monitored: $manga->isMonitored()
                ),
                $mangas
            ),
            total: $total,
            page: $query->page,
            limit: $query->limit
        );
    }
}
