<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules;

final class RuleDefinition
{
    public function __construct(
        private readonly string $ruleId,
        private readonly string $name,
        private readonly array $conditions = [],
        private readonly array $actions = [],
        private readonly int $priority = 100,
        private readonly string $status = 'active',
        private readonly string $version = '1.0.0',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $ruleId, string $name, array $conditions = [], array $actions = [], int $priority = 100, string $version = '1.0.0'): self
    {
        return new self($ruleId, $name, $conditions, $actions, $priority, 'active', $version, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['ruleId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (array) ($data['conditions'] ?? []),
            (array) ($data['actions'] ?? []),
            (int) ($data['priority'] ?? 100),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['version'] ?? '1.0.0'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function ruleId(): string { return $this->ruleId; }
    public function priority(): int { return $this->priority; }
    public function active(): bool { return $this->status === 'active'; }

    public function matches(array $facts): bool
    {
        if (!$this->active()) {
            return false;
        }

        foreach ($this->conditions as $condition) {
            $ruleCondition = RuleCondition::fromArray((array) $condition);
            if (!$ruleCondition->evaluate($facts)) {
                return false;
            }
        }

        return true;
    }

    public function actions(): array
    {
        return array_map(static fn (array $action): RuleAction => RuleAction::fromArray($action), $this->actions);
    }

    public function toArray(): array
    {
        return [
            'ruleId' => $this->ruleId,
            'name' => $this->name,
            'conditions' => $this->conditions,
            'actions' => $this->actions,
            'priority' => $this->priority,
            'status' => $this->status,
            'active' => $this->active(),
            'version' => $this->version,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
