<?php
declare(strict_types=1);

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

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

final class QueueConsumerBatchEngine
{
    private QueueConsumerBatchStatistics $statistics;

    public function __construct(private readonly QueueConsumer $consumer)
    {
        $this->statistics = new QueueConsumerBatchStatistics();
    }

    public function consume(QueueConsumerBatchOptions $options, ?callable $handler = null): QueueConsumerBatchResult
    {
        $results = [];
        $startedAt = date('c');

        for ($i = 0; $i < $options->limitValue(); $i++) {
            $result = $this->consumer->consume($handler);

            if (!$result->acknowledged() && !$result->failed()) {
                if ($options->recordEmpty()) {
                    $results[] = $result;
                }
                break;
            }

            $results[] = $result;

            if ($result->failed() && $options->stopOnFailure()) {
                break;
            }
        }

        $batch = QueueConsumerBatchResult::fromResults($results, $startedAt, date('c'));
        $this->statistics = $this->statistics->record($batch);

        return $batch;
    }

    public function statistics(): QueueConsumerBatchStatistics
    {
        return $this->statistics;
    }
}
