<?php

namespace PloverCRM\Modules\Automations\Services;

/**
 * Evaluates automation conditions against a normalized payload.
 */
class AutomationConditionEvaluator
{
    public static function passes(array $conditions, array $payload): bool
    {
        foreach ($conditions as $condition) {
            if (!self::evaluate($condition, $payload)) {
                return false;
            }
        }

        return true;
    }

    private static function evaluate(array $condition, array $payload): bool
    {
        $field = $condition['field'] ?? '';
        $operator = $condition['operator'] ?? '';
        $expected = $condition['value'] ?? null;
        $actual = self::resolveField($payload, $field);

        switch ($operator) {
            case 'equals':
                return (string) $actual === (string) $expected;

            case 'not_equals':
                return (string) $actual !== (string) $expected;

            case 'contains_any':
                if (!is_array($actual) || !is_array($expected)) {
                    return false;
                }

                return !empty(array_intersect($actual, $expected));

            case 'contains_none':
                if (!is_array($actual) || !is_array($expected)) {
                    return true;
                }

                return empty(array_intersect($actual, $expected));
        }

        return false;
    }

    private static function resolveField(array $payload, string $field)
    {
        $segments = explode('.', $field);
        $value = $payload;

        foreach ($segments as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return null;
            }

            $value = $value[$segment];
        }

        return $value;
    }
}
