<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\ApiPlatform\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\ProjectManagement\Domain\Entity\Workflow;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * @implements ProcessorInterface<Workflow, void>
 */
final readonly class WorkflowDeleteProcessor implements ProcessorInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager,
    ) {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        /** @var Workflow $workflow */
        $workflow = $data;

        $count = (int) $this->entityManager->getConnection()->fetchOne(
            'SELECT COUNT(*) FROM project WHERE workflow_id = :id',
            ['id' => $workflow->getId()],
        );

        if ($count > 0) {
            throw new HttpException(409, sprintf(
                'Workflow used by %d project(s). Reassign them before deleting.',
                $count,
            ));
        }

        $this->entityManager->remove($workflow);
        $this->entityManager->flush();
    }
}
