<?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\ObjectRankedInvocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectRecycledInvocation;
use idoit\Module\SyneticsFlows\Automation\TriggerService;
use isys_cmdb_dao;
use isys_module_synetics_flows;

class ObjectRankedConnect
{
    private static function getContextCustomers()
    {
        return [
            Context::CONTEXT_RANK_OBJECT,
            Context::CONTEXT_RANK_OBJECT_ARCHIVED,
            Context::CONTEXT_RANK_OBJECT_DELETED,
            Context::CONTEXT_RANK_OBJECT_RECYCLED,
        ];
    }

    public function __construct(private TriggerService $service)
    {
    }

    public function __invoke(string $type, isys_cmdb_dao $cmdbDao, int $direction, ?array $objectsIds = []): void
    {
        if (!Connect::supportsContext(self::getContextCustomers())) {
            return;
        }

        foreach($objectsIds as $objectId) {
            $objectData = $cmdbDao->get_object($objectId)->get_row();
            if ($direction === C__CMDB__RANK__DIRECTION_RECYCLE) {
                $this->service->invoke(
                    new ObjectRecycledInvocation(
                        (int) $objectData['isys_obj__status'],
                        new ObjectContext("$objectId", "{$objectData['isys_obj_type__id']}")
                    )
                );
                continue;
            }
            $this->service->invoke(
                new ObjectRankedInvocation(
                    (int) $objectData['isys_obj__status'],
                    new ObjectContext("$objectId", "{$objectData['isys_obj_type__id']}")
                )
            );
        }
    }
}
