<?php

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Context\Context;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectUpdatedInvocation;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_cmdb_dao;
use isys_module_synetics_flows;

class ObjectUpdatedConnect
{
    private static function getContextCustomers()
    {
        return [
            Context::CONTEXT_RANK_CATEGORY,
            Context::CONTEXT_DAO_UPDATE,
            Context::CONTEXT_RANK_OBJECT,
        ];
    }

    public function __construct(private TriggerService $service, private isys_cmdb_dao $cmdbDao)
    {
    }

    public function __invoke(string $type, array $objIdArray, mixed $changedBy = null, mixed $fromLastLog = null): void
    {
        if (!isys_module_synetics_flows::isLicensed()) {
            return;
        }

        if (!Connect::supportsContext(self::getContextCustomers())) {
            return;
        }

        foreach ($objIdArray as $objectId) {
            $objectData = $this->cmdbDao->get_object($objectId)->get_row();

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

            $this->service->invoke(new ObjectUpdatedInvocation($objectData['isys_obj__title'], new ObjectContext("$objectId", "{$objectData['isys_obj_type__id']}")));
        }
    }
}
