<?php
declare(strict_types=1);

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

final class CommandResult
{
    public function __construct(
        private readonly string $commandId,
        private readonly string $commandType,
        private readonly bool $handled,
        private readonly bool $successful,
        private readonly string $eventId = '',
        private readonly string $eventType = '',
        private readonly string $message = '',
        private readonly float $dispatchTimeMs = 0.0,
        private readonly string $createdAt = ''
    ) {}

    public static function handled(CommandMessage $command, string $eventId, string $eventType, float $dispatchTimeMs): self
    {
        return new self(
            $command->commandId(),
            $command->commandType(),
            true,
            true,
            $eventId,
            $eventType,
            'command handled',
            $dispatchTimeMs,
            date('c')
        );
    }

    public static function failed(CommandMessage $command, string $message, float $dispatchTimeMs): self
    {
        return new self(
            $command->commandId(),
            $command->commandType(),
            false,
            false,
            '',
            '',
            $message,
            $dispatchTimeMs,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['commandId'] ?? ''),
            (string) ($data['commandType'] ?? ''),
            (bool) ($data['handled'] ?? false),
            (bool) ($data['successful'] ?? false),
            (string) ($data['eventId'] ?? ''),
            (string) ($data['eventType'] ?? ''),
            (string) ($data['message'] ?? ''),
            (float) ($data['dispatchTimeMs'] ?? 0.0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function isHandled(): bool { return $this->handled; }
    public function successful(): bool { return $this->successful; }

    public function toArray(): array
    {
        return [
            'commandId' => $this->commandId,
            'commandType' => $this->commandType,
            'handled' => $this->handled,
            'successful' => $this->successful,
            'eventId' => $this->eventId,
            'eventType' => $this->eventType,
            'message' => $this->message,
            'dispatchTimeMs' => round($this->dispatchTimeMs, 3),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
