<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules;

final class RuleEvaluationResult
{
    public function __construct(
        private readonly string $resultId,
        private readonly string $ruleSetId,
        private readonly array $matchedRules = [],
        private readonly array $actions = [],
        private readonly array $decisionOutputs = [],
        private readonly bool $matched = false,
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $ruleSetId, array $matchedRules, array $actions, array $decisionOutputs = []): self
    {
        return new self(
            'rule_eval_' . substr(hash('sha256', $ruleSetId . json_encode($matchedRules) . microtime(true)), 0, 24),
            $ruleSetId,
            $matchedRules,
            $actions,
            $decisionOutputs,
            $matchedRules !== [] || $decisionOutputs !== [],
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['resultId'] ?? ''),
            (string) ($data['ruleSetId'] ?? ''),
            (array) ($data['matchedRules'] ?? []),
            (array) ($data['actions'] ?? []),
            (array) ($data['decisionOutputs'] ?? []),
            (bool) ($data['matched'] ?? false),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function matched(): bool { return $this->matched; }
    public function actions(): array { return $this->actions; }

    public function toArray(): array
    {
        return [
            'resultId' => $this->resultId,
            'ruleSetId' => $this->ruleSetId,
            'matchedRules' => $this->matchedRules,
            'actions' => $this->actions,
            'decisionOutputs' => $this->decisionOutputs,
            'matched' => $this->matched,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
