<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Domain\Shared\Application\Command\DeleteJobsByCriteria;
use App\Domain\Shared\Application\CommandHandler\DeleteJobsByCriteriaHandler;
use App\Domain\Shared\Domain\Model\JobStatus;
use Symfony\Component\HttpFoundation\RequestStack;

readonly class DeleteJobsByCriteriaProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteJobsByCriteriaHandler $handler,
        private RequestStack $requestStack
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        $request = $this->requestStack->getCurrentRequest();
        $filters = $request ? $request->query->all() : [];

        $statuses = null;
        if (isset($filters['status'])) {
            $statusValues = is_array($filters['status'])
                ? $filters['status']
                : explode(',', $filters['status']);

            $statuses = [];
            foreach ($statusValues as $value) {
                try {
                    $statuses[] = JobStatus::from($value);
                } catch (\ValueError) {
                    // ignore invalid values
                }
            }

            if (empty($statuses)) {
                $statuses = null;
            }
        }

        $this->handler->handle(new DeleteJobsByCriteria(
            statuses: $statuses,
            type: $filters['type'] ?? null,
            createdAfter: isset($filters['createdAfter']) ? new \DateTimeImmutable($filters['createdAfter']) : null,
            createdBefore: isset($filters['createdBefore']) ? new \DateTimeImmutable($filters['createdBefore']) : null,
        ));
    }
}
