<?php
declare(strict_types=1);

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

final class StreamSubscriberResult
{
    public function __construct(
        private readonly string $subscriberId,
        private readonly string $topic,
        private readonly int $consumed = 0,
        private readonly int $acknowledged = 0,
        private readonly int $failed = 0,
        private readonly array $messages = [],
        private readonly float $processingTimeMs = 0.0,
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $subscriberId, string $topic, int $consumed, int $acknowledged, int $failed, array $messages, float $processingTimeMs): self
    {
        return new self($subscriberId, $topic, $consumed, $acknowledged, $failed, $messages, $processingTimeMs, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['subscriberId'] ?? ''),
            (string) ($data['topic'] ?? ''),
            (int) ($data['consumed'] ?? 0),
            (int) ($data['acknowledged'] ?? 0),
            (int) ($data['failed'] ?? 0),
            (array) ($data['messages'] ?? []),
            (float) ($data['processingTimeMs'] ?? 0.0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function consumed(): int { return $this->consumed; }
    public function acknowledged(): int { return $this->acknowledged; }
    public function failed(): int { return $this->failed; }
    public function processingTimeMs(): float { return $this->processingTimeMs; }

    public function toArray(): array
    {
        return [
            'subscriberId' => $this->subscriberId,
            'topic' => $this->topic,
            'consumed' => $this->consumed,
            'acknowledged' => $this->acknowledged,
            'failed' => $this->failed,
            'messages' => $this->messages,
            'processingTimeMs' => round($this->processingTimeMs, 3),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
