<?php
declare(strict_types=1);

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

final class PublisherRecord
{
    public function __construct(
        private readonly string $publisherId,
        private readonly int $published = 0,
        private readonly int $failed = 0,
        private readonly int $bytes = 0,
        private readonly string $status = 'active',
        private readonly string $lastPublishedAt = ''
    ) {}

    public static function create(string $publisherId): self
    {
        return new self($publisherId);
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['publisherId'] ?? ''),
            (int) ($data['published'] ?? 0),
            (int) ($data['failed'] ?? 0),
            (int) ($data['bytes'] ?? 0),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['lastPublishedAt'] ?? '')
        );
    }

    public function publisherId(): string { return $this->publisherId; }

    public function record(PublishResult $result): self
    {
        return new self(
            $this->publisherId,
            $this->published + ($result->published() ? 1 : 0),
            $this->failed + ($result->published() ? 0 : 1),
            $this->bytes + $result->bytes(),
            'active',
            $result->published() ? date('c') : $this->lastPublishedAt
        );
    }

    public function toArray(): array
    {
        return [
            'publisherId' => $this->publisherId,
            'published' => $this->published,
            'failed' => $this->failed,
            'bytes' => $this->bytes,
            'status' => $this->status,
            'lastPublishedAt' => $this->lastPublishedAt,
        ];
    }
}
