<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules;

final class RuleSet
{
    public function __construct(
        private readonly string $ruleSetId,
        private readonly string $name,
        private readonly array $rules = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $ruleSetId, string $name, array $rules = []): self
    {
        return new self($ruleSetId, $name, $rules, 'active', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['ruleSetId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (array) ($data['rules'] ?? []),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

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

    /** @return RuleDefinition[] */
    public function rules(): array
    {
        $rules = array_map(static fn (array $rule): RuleDefinition => RuleDefinition::fromArray($rule), $this->rules);
        usort($rules, static fn (RuleDefinition $a, RuleDefinition $b): int => $a->priority() <=> $b->priority());
        return $rules;
    }

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