<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\GetMangaList;
use App\Domain\Manga\Application\QueryHandler\GetMangaListHandler;
use App\Domain\Manga\Domain\Model\Manga;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaCollection;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\MangaListItem;

readonly class GetMangaListStateProvider implements ProviderInterface
{
    public function __construct(
        private GetMangaListHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): MangaCollection
    {
        $page = $context['filters']['page'] ?? 1;
        $limit = $context['filters']['limit'] ?? 20;
        $sortBy = $context['filters']['sortBy'] ?? 'title';
        $sortOrder = $context['filters']['sortOrder'] ?? 'asc';

        $query = new GetMangaList($page, $limit, $sortBy, $sortOrder);
        $response = $this->handler->handle($query);

        return new MangaCollection(
            items: array_map(
                fn (Manga $manga) => $this->createMangaListItem(
                    $manga,
                    $response->chapterCounts[$manga->getId()->getValue()] ?? []
                ),
                $response->mangas
            ),
            total: $response->total,
            page: $response->page,
            limit: $response->limit,
            hasNextPage: $response->hasNextPage(),
            hasPreviousPage: $response->hasPreviousPage()
        );
    }

    private function createMangaListItem(Manga $manga, array $counts = []): MangaListItem
    {
        return new MangaListItem(
            id: $manga->getId()->getValue(),
            title: $manga->getTitle()->getValue(),
            description: $manga->getDescription(),
            slug: $manga->getSlug()->getValue(),
            imageUrl: $manga->getImageUrl(),
            thumbnailUrl: $manga->getImageUrls()->getThumbnail(),
            author: $manga->getAuthor(),
            publicationYear: $manga->getPublicationYear(),
            genres: $manga->getGenres(),
            status: $manga->getStatus(),
            rating: $manga->getRating(),
            createdAt: $manga->getCreatedAt(),
            monitored: $manga->getMonitoringStatus()->isEnabled(),
            chaptersTotal: $counts['total'] ?? 0,
            chaptersScraped: $counts['scraped'] ?? 0,
        );
    }
}
