<?php
declare(strict_types=1);

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

final class DomainEventDispatchResult
{
    public function __construct(
        private readonly string $dispatchId,
        private readonly string $eventId,
        private readonly string $listenerId,
        private readonly bool $dispatched,
        private readonly bool $successful,
        private readonly string $message = '',
        private readonly float $dispatchTimeMs = 0.0,
        private readonly string $createdAt = ''
    ) {}

    public static function dispatched(DomainEventEnvelope $event, DomainEventListener $listener, float $dispatchTimeMs): self
    {
        return new self(
            'domain_dispatch_' . substr(hash('sha256', $event->eventId() . $listener->listenerId()), 0, 24),
            $event->eventId(),
            $listener->listenerId(),
            true,
            true,
            'domain event dispatched',
            $dispatchTimeMs,
            date('c')
        );
    }

    public static function skipped(DomainEventEnvelope $event, string $reason): self
    {
        return new self(
            'domain_dispatch_' . substr(hash('sha256', $event->eventId() . $reason), 0, 24),
            $event->eventId(),
            '',
            false,
            false,
            $reason,
            0.0,
            date('c')
        );
    }

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

    public function isDispatched(): bool { return $this->dispatched; }
    public function successful(): bool { return $this->successful; }

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