<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Scraping\Application\Query\GetMangaPreferredSources;
use App\Domain\Scraping\Application\QueryHandler\GetMangaPreferredSourcesHandler;
use App\Domain\Scraping\Infrastructure\ApiPlatform\Dto\MangaPreferredSourcesDetail;

final class GetMangaPreferredSourcesStateProvider implements ProviderInterface
{
    public function __construct(
        private readonly GetMangaPreferredSourcesHandler $queryHandler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): MangaPreferredSourcesDetail
    {
        $mangaId = $uriVariables['id'] ?? null;

        if (!$mangaId) {
            throw new \InvalidArgumentException('Manga ID is required');
        }

        $query = new GetMangaPreferredSources((string) $mangaId);
        $response = $this->queryHandler->handle($query);

        // Convertir les objets Source en array pour l'API
        $sourcesData = array_map(function ($source) {
            return [
                'id' => $source->getId()->getValue(),
                'name' => $source->getName(),
                'baseUrl' => $source->getBaseUrl(),
                'description' => $source->getDescription(),
                'isActive' => $source->isActive()
            ];
        }, $response->sources);

        return new MangaPreferredSourcesDetail(
            $response->mangaId,
            $sourcesData,
            $response->hasPreferredSources
        );
    }
}
