<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Trigger\ConditionMatcher;

use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\CmdbCondition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\Condition;
use idoit\Module\SyneticsFlows\Automation\Trigger\ConditionBuilder\ConditionBuilder;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\InvocationContext;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\ObjectContext;
use idoit\Module\SyneticsFlows\Model\CiObjectDao;

class ObjectBasedConditionMatcher implements ConditionMatcher
{
    /**
     * @param ConditionBuilder $conditionBuilder
     * @param CiObjectDao $objectDao
     */
    public function __construct(private ConditionBuilder $conditionBuilder, private CiObjectDao $objectDao)
    {
    }

    /**
     * @param Condition $condition
     * @param Invocation $invocation
     * @return bool
     */
    public function isMatched(Condition $condition, Invocation $invocation): bool
    {
        if (!$condition instanceof CmdbCondition) {
            return false;
        }

        $context = $invocation->getContext();

        if (!$context instanceof InvocationContext) {
            return false;
        }

        $conditions = [];

        if ($context instanceof ObjectContext) {
            $objectId = $this->objectDao->convert_sql_int($context->getObjectId());
            $conditions[] = "isys_obj__id = $objectId";
        }

        $sql = $this->conditionBuilder->buildSqlCriteria('isys_obj__id', $condition->getCriteria());
        $conditions[] = "($sql)";
        $ids = $this->objectDao->getObjectsIdsByCondition(join(' AND ', $conditions));

        return !empty($ids);
    }

    /**
     * @param Condition $condition
     * @param Invocation $invocation
     * @return bool
     */
    public function supports(Condition $condition, Invocation $invocation): bool
    {
        return $condition instanceof CmdbCondition;
    }
}
