<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Scraping\Application\Command\TestScraperConfiguration;
use App\Domain\Scraping\Application\CommandHandler\TestScraperConfigurationHandler;
use App\Domain\Scraping\Infrastructure\ApiPlatform\Resource\TestScraperConfigurationRequest;
use App\Domain\Scraping\Infrastructure\ApiPlatform\Resource\TestScraperConfigurationResource;

readonly class TestScraperConfigurationStateProcessor implements ProcessorInterface
{
    public function __construct(
        private TestScraperConfigurationHandler $handler
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): TestScraperConfigurationResource
    {
        assert($data instanceof TestScraperConfigurationRequest);

        // Conversion de la requête en Command
        $command = new TestScraperConfiguration(
            baseUrl: $data->baseUrl,
            chapterUrlFormat: $data->chapterUrlFormat,
            scrapingType: $data->scrapingType,
            testUrl: $data->testUrl,
            mangaSlug: $data->mangaSlug,
            chapterNumber: $data->chapterNumber,
            imageSelector: $data->imageSelector,
            nextPageSelector: $data->nextPageSelector,
            chapterSelector: $data->chapterSelector,
        );

        // Exécution du CommandHandler
        $response = $this->handler->handle($command);

        // Conversion de la Response en Resource
        return new TestScraperConfigurationResource(
            success: $response->success,
            imageUrls: $response->imageUrls,
            totalImages: $response->totalImages,
            testedUrl: $response->testedUrl,
            scrapingType: $response->scrapingType,
            errors: $response->errors,
        );
    }
}
