<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Query;

final class ReadModelDefinition
{
    public function __construct(
        private readonly string $readModelId,
        private readonly string $projectionId,
        private readonly string $name,
        private readonly array $fields = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

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

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

    public function readModelId(): string { return $this->readModelId; }
    public function projectionId(): string { return $this->projectionId; }
    public function name(): string { return $this->name; }
    public function fields(): array { return $this->fields; }
    public function active(): bool { return $this->status === 'active'; }

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