<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\ConnectSignal;

use idoit\Context\Context;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\CategoryEntryRankedInvocation;
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 CategoryEntryRankedConnect
{
    const ENTRY_PURGED_STATUS = '5';

    private static function getContextCustomers()
    {
        return [
            Context::CONTEXT_RANK_CATEGORY_ARCHIVED,
            Context::CONTEXT_RANK_CATEGORY_DELETED,
            Context::CONTEXT_RANK_CATEGORY_PURGED,
            Context::CONTEXT_RANK_CATEGORY_RECYCLED,
            Context::CONTEXT_DAO_UPDATE,
        ];
    }

    public function __construct(private TriggerService $service)
    {
    }

    public function __invoke(
        string $type,
        isys_cmdb_dao_category $dao,
        string $table,
        mixed $result,
        mixed $direction,
        ?array $entriesIds = []
    ): void
    {
        if (!isys_module_synetics_flows::isLicensed()) {
            return;
        }

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

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

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

        $context = new ObjectContext("{$objectData['isys_obj__id']}", "{$objectData['isys_obj__isys_obj_type__id']}");

        foreach ($entriesIds as $id) {
            $entryStatus = $dao->cat_get_status_by_id($table, (int)$id) ?? self::ENTRY_PURGED_STATUS;
            $this->service->invoke(
                new CategoryEntryRankedInvocation((int) $id, $dao->get_category_const(), (int)$entryStatus, $context)
            );
        }
    }
}
