<?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\CommandTaskScheduleInput;
use App\Dto\Output\CommandTaskScheduleOutput;
use App\Repository\CommandTaskScheduleRepository;
use App\Service\CreateTraceService;

readonly class CommandTaskScheduleProcessor implements ProcessorInterface
{

    public function __construct(
        private CommandTaskScheduleRepository               $commandTaskScheduleRepository,
        private ValidatorInterface                          $validator,
    )
    {
    }

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

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

        $task = $data->createOrUpdateEntity($entity);
        $this->validator->validate($task);
        $this->commandTaskScheduleRepository->save($task);

        return new CommandTaskScheduleOutput($task);
    }

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

        return null;
    }
}