<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Manga\Application\Query\GetMangaChapters;
use App\Domain\Manga\Application\QueryHandler\GetMangaChaptersHandler;
use App\Domain\Manga\Application\Response\ChapterResponse;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\ChapterCollection;
use App\Domain\Manga\Infrastructure\ApiPlatform\Dto\ChapterListItem;

readonly class GetMangaChaptersStateProvider implements ProviderInterface
{
    public function __construct(
        private GetMangaChaptersHandler $handler
    ) {
    }

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

        $query = new GetMangaChapters(
            mangaId: $uriVariables['id'],
            page: $page,
            limit: $limit,
            sortOrder: $sortOrder
        );

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

        return new ChapterCollection(
            items: array_map(
                fn (ChapterResponse $chapter) => $this->createChapterListItem($chapter),
                $response->chapters
            ),
            total: $response->total,
            page: $response->page,
            limit: $response->limit,
            hasNextPage: $response->hasNextPage(),
            hasPreviousPage: $response->hasPreviousPage()
        );
    }

    private function createChapterListItem(ChapterResponse $chapter): ChapterListItem
    {
        return new ChapterListItem(
            id: $chapter->id,
            number: $chapter->number,
            title: $chapter->title,
            volume: $chapter->volume,
            isVisible: $chapter->isVisible,
            isAvailable: $chapter->pagesDirectory !== null,
            createdAt: $chapter->createdAt,
            isVolumeGroup: $chapter->isVolumeGroup,
            volumeChaptersRange: $chapter->volumeChaptersRange,
            volumeChapterCount: $chapter->volumeChapterCount,
        );
    }
}
