<?php

namespace App\State\Processor;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Input\OperativeSystemInput;
use App\Dto\Output\OperativeSystemOutput;
use App\Repository\OperativeSystemRepository;

readonly class OperativeSystemProcessor implements ProcessorInterface
{
    public function __construct(
        private OperativeSystemRepository       $operativeSystemRepository,
        private ValidatorInterface              $validator
    )
    {
    }

    /**
     * @throws \Exception
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
    {
        switch ($operation){
            case $operation instanceof Post:
            case $operation instanceof Put:
            case $operation instanceof Patch:
                return $this->processCreateOrUpdate($data, $operation, $uriVariables, $context);
            case $operation instanceof Delete:
                return $this->processDelete($data, $operation, $uriVariables, $context);
        }
    }

    /**
     * @throws \Exception
     */
    private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): OperativeSystemOutput
    {
        if (!($data instanceof OperativeSystemInput)) {
            throw new \Exception(sprintf('data is not instance of %s', OperativeSystemInput::class));
        }

        $entity = null;
        if (isset($uriVariables['uuid'])) {
            $entity = $this->operativeSystemRepository->findOneByUuid($uriVariables['uuid']);
        }

        $operativeSystem = $data->createOrUpdateEntity($entity);
        $this->validator->validate($operativeSystem);
        $this->operativeSystemRepository->save($operativeSystem);

        return new OperativeSystemOutput($operativeSystem);
    }

    private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        $user = $this->operativeSystemRepository->findOneByUuid($uriVariables['uuid']);
        $this->operativeSystemRepository->delete($user);

        return null;
    }
}
