<?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\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Messenger\MessageBusInterface;

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

    /**
     * @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->hub->publish(new Update(
            'jobs/activity',
            json_encode([
                'type' => 'job.created',
                'id' => $job->id,
                'type_job' => $job->type,
                'status' => $job->status->value,
                'createdAt' => $job->createdAt->format('c'),
                'context' => $job->context,
                'attempts' => $job->attempts,
                'maxAttempts' => $job->maxAttempts,
            ])
        ));

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