<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Context\Context;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\CategoryUpdatedInvocation;
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_cmdb_dao_category;
use isys_module_synetics_flows;

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

    public function __construct(private TriggerService $service)
    {
    }

    /**
     * @param string                 $type
     * @param isys_cmdb_dao_category $dao
     * @param string|int|bool|null   $entryId
     * @param string|bool|null       $saveSuccess
     * @param string|int|bool|null   $objectId
     * @param array                  $posts
     * @param array                  $changes
     *
     * @return void
     */
    public function __invoke(string $type, isys_cmdb_dao_category $dao, mixed $entryId, mixed $saveSuccess, mixed $objectId, array $posts, array $changes): void
    {
        if (!Connect::supportsContext(self::getContextCustomers())) {
            return;
        }

        $categoryConstant = $dao->get_category_const();
        $className = get_class($dao);
        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;
        }

        $attributes = array_map(function ($key) use ($className, $categoryConstant) {
            if (substr_count($key, '::') > 1) {
                $key = substr($key, 0, strrpos($key, '::'));
            }
            return str_replace("{$className}::", "{$categoryConstant}.", $key);
        }, array_keys($changes));
        $objectTypeId = $objectData['isys_obj__isys_obj_type__id'];

        $this->service->invoke(new CategoryUpdatedInvocation($categoryConstant, "{$dao->get_category_type()}", $attributes, new ObjectContext("{$objectId}", "{$objectTypeId}")));
    }
}
