<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Context\Context;
use idoit\Module\Cmdb\Interfaces\ObjectBrowserAssignedEntries;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\CategoryCreatedInvocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_cmdb_dao_category;
use isys_module_synetics_flows;

class CategoryCreatedConnect
{
    private static function getContextCustomers()
    {
        return [
            Context::CONTEXT_DAO_CREATE,
            Context::CONTEXT_DAO_UPDATE,
        ];
    }

    public function __construct(private TriggerService $service)
    {
    }

    public function __invoke(
        string $type,
        isys_cmdb_dao_category $dao,
        mixed $entryId,
        mixed $isNewId,
        mixed $objectId,
        ?array $data = [],
        ?array $changes = []
    ): void
    {
        if (!isys_module_synetics_flows::isLicensed()) {
            return;
        }

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

        if (isset($changes[0])) {
            $changes = $changes[0];
        }

        if (empty($changes) || !is_numeric($objectId)) {
            return;
        }

        if (isset($changes[0])) {
            $changes = $changes[0];
        }

        if (empty($changes)) {
            return;
        }

        $objectData = $dao->get_object((int)$objectId)->get_row();

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

        $objectType = $objectData['isys_obj__isys_obj_type__id'];

        if ($dao instanceof ObjectBrowserAssignedEntries) {
            $assignedEntries = (string)current($changes)['to'];
            $entryIds = array_filter(explode(',', $assignedEntries));

            foreach ($entryIds as $entryId) {
                $this->service->invoke(
                    new CategoryCreatedInvocation($dao->get_category_const(), new ObjectContext("$objectId", "$objectType"))
                );
            }

            return;
        }

        $this->service->invoke(
            new CategoryCreatedInvocation($dao->get_category_const(), new ObjectContext("$objectId", "$objectType"))
        );
    }
}
