<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Consumer\Batch;

use PpPhp\Core\Platform\Event\Consumer\QueueConsumerResult;

final class QueueConsumerBatchResult
{
    public function __construct(private readonly array $results = [], private readonly string $startedAt = '', private readonly string $finishedAt = '') {}

    public static function fromResults(array $results, string $startedAt = '', string $finishedAt = ''): self
    {
        return new self($results, $startedAt, $finishedAt);
    }

    public function results(): array { return $this->results; }
    public function total(): int { return count($this->results); }

    public function acknowledged(): int
    {
        return count(array_filter($this->results, static fn ($result): bool => $result instanceof QueueConsumerResult && $result->acknowledged()));
    }

    public function failed(): int
    {
        return count(array_filter($this->results, static fn ($result): bool => $result instanceof QueueConsumerResult && $result->failed()));
    }

    public function empty(): bool
    {
        return $this->total() === 0;
    }

    public function ok(): bool
    {
        return $this->failed() === 0;
    }

    public function partial(): bool
    {
        return $this->acknowledged() > 0 && $this->failed() > 0;
    }

    public function toArray(): array
    {
        return [
            'total' => $this->total(),
            'acknowledged' => $this->acknowledged(),
            'failed' => $this->failed(),
            'ok' => $this->ok(),
            'partial' => $this->partial(),
            'startedAt' => $this->startedAt !== '' ? $this->startedAt : date('c'),
            'finishedAt' => $this->finishedAt !== '' ? $this->finishedAt : date('c'),
            'results' => array_map(static fn ($result): array => $result instanceof QueueConsumerResult ? $result->toArray() : [], $this->results),
        ];
    }
}
