<?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\OgBoot\PxeTemplate\PostAction;
use App\Dto\Input\PxeTemplateInput;
use App\Dto\Output\PxeTemplateOutput;
use App\Repository\PxeTemplateRepository;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

readonly class PxeTemplateProcessor implements ProcessorInterface
{
    public function __construct(
        private PxeTemplateRepository            $pxeTemplateRepository,
        private ValidatorInterface               $validator,
        private PostAction                       $postAction,
    )
    {
    }

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

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

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

        if (!$pxeTemplate->getId() ) {
            $this->postAction->__invoke($pxeTemplate);
        }

        $this->pxeTemplateRepository->save($pxeTemplate);

        return new PxeTemplateOutput($pxeTemplate);
    }

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

        return null;
    }
}
