<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Context\Context;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectCreatedInvocation;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_application;
use isys_module_synetics_flows;

class ObjectCreatedConnect
{
    private static function getContextCustomers()
    {
        return [
            Context::CONTEXT_OBJECT_CREATE,
            CONTEXT::CONTEXT_DAO_UPDATE,
        ];
    }

    public function __construct(private TriggerService $service)
    {
    }

    public function __invoke(string $type, mixed $objectId, mixed $systemId, mixed $objectType, mixed $title): void
    {
        if (!Connect::supportsContext(self::getContextCustomers())) {
            return;
        }

        $objectType = is_int($objectType) ? $objectType :
            (is_numeric($objectType) ? (int)$objectType :
                (is_string($objectType) && defined($objectType) ? constant($objectType) :
                    null)
            );

        if (!is_numeric($objectId) || $objectType === null) {
            return;
        }

        $objectData = isys_application::instance()->container->get('cmdb_dao')
            ->get_object((int)$objectId)->get_row();

        // Do not trigger on templates or Mass change templates
        if (!$objectData || in_array($objectData['isys_obj__status'], Connect::getBlockedStates())) {
            return;
        }

        $this->service->invoke(new ObjectCreatedInvocation("$title", new ObjectContext("$objectId", "$objectType")));
    }
}
