<?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\SoftwareInput;
use App\Dto\Output\SoftwareOutput;
use App\Repository\SoftwareRepository;

readonly class SoftwareProcessor implements ProcessorInterface
{
    public function __construct(
        private SoftwareRepository $softwareRepository,
        private ValidatorInterface $validator
    )
    {
    }

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

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

        $software = $data->createOrUpdateEntity($entity);
        $this->validator->validate($software);
        $this->softwareRepository->save($software);

        return new SoftwareOutput($software);
    }

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

        return null;
    }
}
