<?php

namespace App\State\Processor;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Service\OnChange\OnChangeContext;
use App\Service\OnChange\OnChangeDefault;
use App\Service\OnChange\OnChangeInterface;
use RuntimeException;
use Symfony\Contracts\Service\Attribute\Required;

/**
 * Classe de base pour les Processor classiques, proposant des hook pre et post persist,
 * ainsi que certaines méthodes liées au contexte de la mise à jour.
 */
class EntityProcessor implements ProcessorInterface
{
    // <-- dependencies injections
    protected ProcessorInterface $persistProcessor;
    protected OnChangeInterface $onChange;

    public function __construct(
        OnChangeDefault $onChange
    ) {
        $this->onChange = $onChange;
    }

    #[Required]
    public function setProcessorInterface(ProcessorInterface $persistProcessor): void {$this->persistProcessor = $persistProcessor;}

    /**
     * Persiste l'entité et déclenche les différents hooks de la classe OnChangeInterface définie par le data persister
     *
     * @param mixed $data
     * @param Operation $operation
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     * @return object
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): object
    {
        if($operation instanceof Delete){
            throw new RuntimeException('not supported', 500);
        }

        $onChangeContext = new OnChangeContext($context);

        $this->onChange->validate($data, $onChangeContext);

        $data = $this->onChange->preProcess($data, $onChangeContext);

        $this->onChange->beforeChange($data, $onChangeContext);

        $result = $this->persistProcessor->process($data,  $operation,  $uriVariables,  $context);

        $this->onChange->onChange($data, $onChangeContext);

        return $result;
    }
}
