<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Setting\Application\Query\GetContentSourceQuery;
use App\Domain\Setting\Application\QueryHandler\GetContentSourceQueryHandler;
use App\Domain\Setting\Domain\Exception\ContentSourceNotFoundException;
use App\Domain\Setting\Infrastructure\ApiPlatform\Resource\GetContentSourceResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class GetContentSourceStateProvider implements ProviderInterface
{
    public function __construct(
        private GetContentSourceQueryHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?GetContentSourceResource
    {
        try {
            $query = new GetContentSourceQuery($uriVariables['id']);
            $response = $this->handler->handle($query);

            return new GetContentSourceResource(
                id: $response->id,
                baseUrl: $response->baseUrl,
                chapterUrlFormat: $response->chapterUrlFormat,
                scrapingType: $response->scrapingType,
                imageSelector: $response->imageSelector,
                nextPageSelector: $response->nextPageSelector,
                chapterSelector: $response->chapterSelector,
                cleanBaseUrl: $response->cleanBaseUrl,
                testSlug: $response->testSlug,
                testChapterNumber: $response->testChapterNumber,
                healthStatus: $response->healthStatus,
                healthLastTestedAt: $response->healthLastTestedAt,
                healthLastError: $response->healthLastError,
            );
        } catch (ContentSourceNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
    }
}
