<?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\OrganizationalUnitInput;
use App\Dto\Output\OrganizationalUnitOutput;
use App\Repository\OrganizationalUnitRepository;
use App\Service\ChangeClientNetworkSettingsService;

readonly class OrganizationalUnitProcessor implements ProcessorInterface
{
    public function __construct(
        private OrganizationalUnitRepository       $organizationalUnitRepository,
        private ValidatorInterface                 $validator,
        private ChangeClientNetworkSettingsService $changeClientNetworkSettingsService,
    )
    {
    }

    /**
     * @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 = []): OrganizationalUnitOutput
    {
        if (!($data instanceof OrganizationalUnitInput)) {
            throw new \Exception(sprintf('data is not instance of %s', OrganizationalUnitInput::class));
        }

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

        $organizationalUnit = $data->createOrUpdateEntity($entity);
        $this->validator->validate($organizationalUnit, ['groups' => ['organizational-unit:write']]);
        $this->organizationalUnitRepository->save($organizationalUnit);

        //$this->changeClientNetworkSettingsService->__invoke($organizationalUnit);

        return new OrganizationalUnitOutput($organizationalUnit);
    }

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

        return null;
    }
}
