<?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\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 ObjectContext) {
            return false;
        }

        $criteria = $condition->getCriteria();
        $sql = $this->conditionBuilder->buildSqlCriteria('isys_obj__id', $criteria);
        $id = $context->getObjectId();
        $cleanId = $this->objectDao->convert_sql_int($id);
        $ids = $this->objectDao->getObjectsIdsByCondition("isys_obj__id = $cleanId AND ($sql)");

        return !empty($ids);
    }

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