<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Setting\Application\Query\ListContentSourceQuery;
use App\Domain\Setting\Application\QueryHandler\ListContentSourceQueryHandler;
use App\Domain\Setting\Infrastructure\ApiPlatform\Resource\GetContentSourceResource;

readonly class ListContentSourceStateProvider implements ProviderInterface
{
    public function __construct(
        private ListContentSourceQueryHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $query = new ListContentSourceQuery();
        $response = $this->handler->handle($query);

        return array_map(
            fn ($contentSourceResponse) => new GetContentSourceResource(
                id: $contentSourceResponse->id,
                baseUrl: $contentSourceResponse->baseUrl,
                chapterUrlFormat: $contentSourceResponse->chapterUrlFormat,
                scrapingType: $contentSourceResponse->scrapingType,
                imageSelector: $contentSourceResponse->imageSelector,
                nextPageSelector: $contentSourceResponse->nextPageSelector,
                chapterSelector: $contentSourceResponse->chapterSelector,
                cleanBaseUrl: $contentSourceResponse->cleanBaseUrl,
                testSlug: $contentSourceResponse->testSlug,
                testChapterNumber: $contentSourceResponse->testChapterNumber,
                healthStatus: $contentSourceResponse->healthStatus,
                healthLastTestedAt: $contentSourceResponse->healthLastTestedAt,
                healthLastError: $contentSourceResponse->healthLastError,
            ),
            $response->contentSources
        );
    }
}
