<?php

namespace idoit\Module\SyneticsFlows\Controller;

use Exception;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ButtonInvocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use idoit\Module\SyneticsFlows\Serialization\Serializer;
use isys_application;
use isys_cmdb_dao;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Trigger controller
 *
 * @package   idoit\Module\synetics_flows\Controller
 * @copyright synetics
 * @license   https://www.i-doit.com/
 */
class TriggerController
{
    private ?TriggerService $service = null;

    public function invoke(string $objectId, Request $request): Response
    {
        $invocation = Serializer::fromJson(ButtonInvocation::class, $request->attributes->all());
        if (!$invocation instanceof ButtonInvocation) {
            return new JsonResponse([]);
        }
        $dao = isys_application::instance()->container->get('cmdb_dao');
        $objTypeId = 0;
        if ($dao instanceof isys_cmdb_dao) {
            $objTypeId = $dao->get_objTypeID((int)$objectId);
        }
        $invocation->setContext(new ObjectContext($objectId, "$objTypeId"));
        $created = $this->getService()->invoke($invocation);

        return new JsonResponse(['ids' => $created]);
    }

    /**
     * @return TriggerService
     *
     * @throws Exception
     */
    private function getService(): TriggerService
    {
        if (!$this->service) {
            $this->service = isys_application::instance()->container->get('idoit.flows.trigger');
        }
        return $this->service;
    }
}
