<?php
declare(strict_types=1);

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

final class CommandMessage
{
    public function __construct(
        private readonly string $commandId,
        private readonly string $commandType,
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly array $payload = [],
        private readonly array $metadata = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $commandType,
        string $aggregateId,
        string $aggregateType,
        array $payload = [],
        array $metadata = []
    ): self {
        return new self(
            'cmd_' . substr(hash('sha256', $commandType . $aggregateId . $aggregateType . json_encode($payload) . microtime(true)), 0, 24),
            $commandType,
            $aggregateId,
            $aggregateType,
            $payload,
            $metadata,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['commandId'] ?? ''),
            (string) ($data['commandType'] ?? ''),
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (array) ($data['payload'] ?? []),
            (array) ($data['metadata'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function commandId(): string { return $this->commandId; }
    public function commandType(): string { return $this->commandType; }
    public function aggregateId(): string { return $this->aggregateId; }
    public function aggregateType(): string { return $this->aggregateType; }
    public function payload(): array { return $this->payload; }
    public function metadata(): array { return $this->metadata; }

    public function toArray(): array
    {
        return [
            'commandId' => $this->commandId,
            'commandType' => $this->commandType,
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'payload' => $this->payload,
            'metadata' => $this->metadata,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
