<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming\Publisher;

final class PublishResult
{
    public function __construct(
        private readonly bool $published,
        private readonly string $messageId = '',
        private readonly string $topic = '',
        private readonly string $status = 'failed',
        private readonly string $reason = '',
        private readonly float $publishTimeMs = 0.0,
        private readonly int $bytes = 0,
        private readonly string $createdAt = ''
    ) {}

    public static function success(string $messageId, string $topic, float $publishTimeMs, int $bytes): self
    {
        return new self(true, $messageId, $topic, 'published', 'published', $publishTimeMs, $bytes, date('c'));
    }

    public static function failure(string $topic, string $reason, float $publishTimeMs = 0.0): self
    {
        return new self(false, '', $topic, 'failed', $reason, $publishTimeMs, 0, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (bool) ($data['published'] ?? false),
            (string) ($data['messageId'] ?? ''),
            (string) ($data['topic'] ?? ''),
            (string) ($data['status'] ?? 'failed'),
            (string) ($data['reason'] ?? ''),
            (float) ($data['publishTimeMs'] ?? 0.0),
            (int) ($data['bytes'] ?? 0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function published(): bool { return $this->published; }
    public function messageId(): string { return $this->messageId; }
    public function topic(): string { return $this->topic; }
    public function publishTimeMs(): float { return $this->publishTimeMs; }
    public function bytes(): int { return $this->bytes; }

    public function toArray(): array
    {
        return [
            'published' => $this->published,
            'messageId' => $this->messageId,
            'topic' => $this->topic,
            'status' => $this->status,
            'reason' => $this->reason,
            'publishTimeMs' => round($this->publishTimeMs, 3),
            'bytes' => $this->bytes,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
