<?php

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Scraping\Application\Command\ScrapeChapter;
use App\Domain\Scraping\Domain\Model\ScrapingJob;
use App\Domain\Scraping\Infrastructure\ApiPlatform\Dto\ScrapeChapterRequest;
use App\Domain\Shared\Domain\Contract\JobRepositoryInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Messenger\MessageBusInterface;

final class ScrapeChapterStateProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly MessageBusInterface $commandBus,
        private readonly JobRepositoryInterface $jobRepository,
    ) {
    }

    /**
     * @param ScrapeChapterRequest $data
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        $jobId = Uuid::uuid4()->toString();
        $job = new ScrapingJob($jobId);
        $job->context['chapterId'] = $data->chapterId;
        $this->jobRepository->save($job);

        $this->commandBus->dispatch(new ScrapeChapter($data->chapterId, $jobId));
    }
}
