<?php

declare(strict_types=1);

namespace WorkforceOS\Services;

final class RuleEngine
{
    public function evaluate(array $rules, array $facts): array
    {
        usort($rules, fn (array $a, array $b): int => ($a['priority'] ?? 100) <=> ($b['priority'] ?? 100));

        $actions = [];
        foreach ($rules as $rule) {
            if ($this->matches($rule['conditions'] ?? [], $facts)) {
                $actions[] = [
                    'rule' => $rule['name'],
                    'action' => $rule['action'],
                    'value' => $rule['value'] ?? null,
                ];
            }
        }

        return $actions;
    }

    private function matches(array $conditions, array $facts): bool
    {
        foreach ($conditions as $field => $condition) {
            $actual = $facts[$field] ?? null;
            $operator = $condition['operator'] ?? '=';
            $expected = $condition['value'] ?? null;

            $matched = match ($operator) {
                '>' => $actual > $expected,
                '>=' => $actual >= $expected,
                '<' => $actual < $expected,
                '<=' => $actual <= $expected,
                '!=' => $actual != $expected,
                default => $actual == $expected,
            };

            if (!$matched) {
                return false;
            }
        }

        return true;
    }
}
