<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\ModelType;
use App\Service\SkeletonStructureService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class ModelTypeProcessor implements ProcessorInterface
{
    public function __construct(
        #[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
        private readonly ProcessorInterface $decorated,
        private readonly SkeletonStructureService $skeletonStructureService,
        private readonly EntityManagerInterface $entityManager,
    ) {}

    /**
     * @param array<string, mixed> $uriVariables
     * @param array<string, mixed> $context
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
    {
        if (!$data instanceof ModelType) {
            return $this->decorated->process($data, $operation, $uriVariables, $context);
        }

        $pendingStructure = $data->getPendingStructure();

        // Persist the entity first (handles all non-skeleton fields)
        $result = $this->decorated->process($data, $operation, $uriVariables, $context);

        // If structure was provided in the payload, write it to skeleton relation tables
        if (null !== $pendingStructure) {
            $this->skeletonStructureService->updateSkeletonRequirements($data, $pendingStructure);
            $data->clearPendingStructure();
            $this->entityManager->flush();
        }

        return $result;
    }
}
