<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\SearchLocalManga;
use App\Domain\Manga\Application\QueryHandler\SearchLocalMangaHandler;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaCollection;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaListItem;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

readonly class SearchLocalMangaStateProvider implements ProviderInterface
{
    public function __construct(
        private SearchLocalMangaHandler $handler
    ) {
    }

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

        if (strlen($query) < 3) {
            throw new BadRequestHttpException('Le terme de recherche doit contenir au moins 3 caractères');
        }

        $page = (int) ($context['filters']['page'] ?? 1);
        if ($page < 1) {
            throw new BadRequestHttpException('Le numéro de page doit être supérieur à 0');
        }

        $limit = (int) ($context['filters']['limit'] ?? 20);

        $searchQuery = new SearchLocalManga($query, $page, $limit);
        $response = $this->handler->handle($searchQuery);

        return new MangaCollection(
            items: array_map(
                fn ($item) => new MangaListItem(
                    id: $item->id,
                    title: $item->title,
                    description: $item->description,
                    slug: $item->slug,
                    imageUrl: $item->imageUrl,
                    thumbnailUrl: $item->thumbnailUrl,
                    author: $item->author,
                    publicationYear: $item->publicationYear,
                    genres: $item->genres,
                    status: $item->status,
                    rating: $item->rating,
                    createdAt: new \DateTimeImmutable()
                ),
                $response->mangas
            ),
            total: $response->total,
            page: $response->page,
            limit: $response->limit,
            hasNextPage: false,
            hasPreviousPage: false
        );
    }
}
