<?php
declare(strict_types=1);

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

final class StoredEvent
{
    public function __construct(
        private readonly int $sequence,
        private readonly string $eventId,
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly int $aggregateVersion,
        private readonly string $eventType,
        private readonly array $payload = [],
        private readonly array $metadata = [],
        private readonly string $recordedAt = ''
    ) {}

    public static function record(
        int $sequence,
        string $aggregateId,
        string $aggregateType,
        int $aggregateVersion,
        string $eventType,
        array $payload = [],
        array $metadata = []
    ): self {
        return new self(
            $sequence,
            'es_evt_' . str_pad((string) $sequence, 10, '0', STR_PAD_LEFT),
            $aggregateId,
            $aggregateType,
            max(1, $aggregateVersion),
            $eventType,
            $payload,
            $metadata,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (int) ($data['sequence'] ?? 0),
            (string) ($data['eventId'] ?? ''),
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (int) ($data['aggregateVersion'] ?? 1),
            (string) ($data['eventType'] ?? ''),
            (array) ($data['payload'] ?? []),
            (array) ($data['metadata'] ?? []),
            (string) ($data['recordedAt'] ?? '')
        );
    }

    public function sequence(): int { return $this->sequence; }
    public function eventId(): string { return $this->eventId; }
    public function aggregateId(): string { return $this->aggregateId; }
    public function aggregateType(): string { return $this->aggregateType; }
    public function aggregateVersion(): int { return $this->aggregateVersion; }
    public function eventType(): string { return $this->eventType; }

    public function toArray(): array
    {
        return [
            'sequence' => $this->sequence,
            'eventId' => $this->eventId,
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'aggregateVersion' => $this->aggregateVersion,
            'eventType' => $this->eventType,
            'payload' => $this->payload,
            'metadata' => $this->metadata,
            'recordedAt' => $this->recordedAt !== '' ? $this->recordedAt : date('c'),
        ];
    }
}
