<?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\Controller\OgDhcp\Subnet\PostAction;
use App\Controller\OgDhcp\Subnet\PutAction;
use App\Dto\Input\SubnetInput;
use App\Dto\Output\SubnetOutput;
use App\Repository\SubnetRepository;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

readonly class SubnetProcessor implements ProcessorInterface
{
    public function __construct(
        private SubnetRepository                 $subnetRepository,
        private ValidatorInterface               $validator,
        private PostAction                       $postAction,
        private PutAction                        $putAction,
    )
    {
    }

    /**
     * @throws \Exception
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): SubnetOutput|null
    {
        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
     * @throws TransportExceptionInterface
     */
    private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): SubnetOutput
    {
        if (!($data instanceof SubnetInput)) {
            throw new \Exception(sprintf('data is not instance of %s', SubnetInput::class));
        }

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

        $subnet = $data->createOrUpdateEntity($entity);
        $this->validator->validate($subnet);

        if (!$subnet->getId() ) {
            $this->postAction->__invoke($subnet);
        } else {
            $this->putAction->__invoke($subnet);
        }

        $this->subnetRepository->save($subnet);

        return new SubnetOutput($subnet);
    }

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

        return null;
    }
}
