<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\Condition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Condition\UserCondition;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class UserConditionMatcher implements ConditionMatcher
{
    public function __construct(private \isys_cmdb_dao_category_s_person_assigned_groups $assignedGroups)
    {
    }

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

        if (in_array($invocation->getContext()->getUserId(), $condition->getUserIds())) {
            return true;
        }

        $assignedGroupsIds = $this->assignedGroups->getAssignedGroupsIDs($invocation->getContext()->getUserId());

        return count(array_intersect($condition->getUserIds(), $assignedGroupsIds)) > 0;

    }

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