<?php
declare(strict_types=1);

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

final class AggregateState
{
    public function __construct(
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly int $version = 0,
        private readonly array $state = [],
        private readonly array $events = [],
        private readonly string $rehydratedAt = ''
    ) {}

    public static function empty(string $aggregateId, string $aggregateType): self
    {
        return new self($aggregateId, $aggregateType, 0, [], [], date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (int) ($data['version'] ?? 0),
            (array) ($data['state'] ?? []),
            (array) ($data['events'] ?? []),
            (string) ($data['rehydratedAt'] ?? '')
        );
    }

    public function aggregateId(): string { return $this->aggregateId; }
    public function aggregateType(): string { return $this->aggregateType; }
    public function version(): int { return max(0, $this->version); }
    public function state(): array { return $this->state; }
    public function events(): array { return $this->events; }

    public function apply(array $event): self
    {
        $payload = (array) ($event['payload'] ?? []);
        $state = array_replace_recursive($this->state, $payload);

        $events = $this->events;
        $events[] = $event;

        return new self(
            $this->aggregateId,
            $this->aggregateType,
            (int) ($event['aggregateVersion'] ?? ($this->version + 1)),
            $state,
            $events,
            date('c')
        );
    }

    public function toArray(): array
    {
        return [
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'version' => $this->version(),
            'state' => $this->state,
            'events' => $this->events,
            'rehydratedAt' => $this->rehydratedAt !== '' ? $this->rehydratedAt : date('c'),
        ];
    }
}
