<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules\Repository;

final class RuleRepositoryEntry
{
    public function __construct(
        private readonly string $entryId,
        private readonly string $ruleId,
        private readonly string $ruleSetId,
        private readonly string $name,
        private readonly string $type = 'rule',
        private readonly string $version = '1.0.0',
        private readonly string $status = 'active',
        private readonly array $metadata = [],
        private readonly string $createdAt = '',
        private readonly string $updatedAt = ''
    ) {}

    public static function create(
        string $ruleId,
        string $ruleSetId,
        string $name,
        string $type = 'rule',
        string $version = '1.0.0',
        array $metadata = []
    ): self {
        return new self(
            'rule_repo_' . substr(hash('sha256', $ruleSetId . $ruleId . $version), 0, 24),
            $ruleId,
            $ruleSetId,
            $name,
            $type,
            $version,
            'active',
            $metadata,
            date('c'),
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['entryId'] ?? ''),
            (string) ($data['ruleId'] ?? ''),
            (string) ($data['ruleSetId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (string) ($data['type'] ?? 'rule'),
            (string) ($data['version'] ?? '1.0.0'),
            (string) ($data['status'] ?? 'active'),
            (array) ($data['metadata'] ?? []),
            (string) ($data['createdAt'] ?? ''),
            (string) ($data['updatedAt'] ?? '')
        );
    }

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

    public function deactivate(): self
    {
        return new self($this->entryId, $this->ruleId, $this->ruleSetId, $this->name, $this->type, $this->version, 'inactive', $this->metadata, $this->createdAt, date('c'));
    }

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