<?php

namespace App\Domain\Manga\Infrastructure\ApiPlatform\State\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\SearchManga;
use App\Domain\Manga\Application\QueryHandler\SearchMangaHandler;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaSearchCollection;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaSearchItem;

readonly class SearchMangaStateProvider implements ProviderInterface
{
    public function __construct(
        private SearchMangaHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): MangaSearchCollection
    {
        $title = $context['filters']['title'] ?? '';

        $query = new SearchManga($title);
        $response = $this->handler->handle($query);

        return new MangaSearchCollection(
            items: array_map(
                fn ($item) => new MangaSearchItem(
                    externalId: $item->externalId,
                    title: $item->title,
                    slug: $item->slug,
                    description: $item->description,
                    author: $item->author,
                    publicationYear: $item->publicationYear,
                    genres: $item->genres,
                    status: $item->status,
                    imageUrl: $item->imageUrl,
                    thumbnailUrl: $item->thumbnailUrl,
                    rating: $item->rating
                ),
                $response->items
            )
        );
    }
}
