<?php
/**
 * LogQueue - Default in-memory queue implementation for Loki logs
 * This is the fallback implementation when no persistent queue is available.
 */

namespace CloudXM\SDK\Queue;

use CloudXM\SDK\Support\HasLogger;

class LogQueue implements LogQueueInterface
{
    use HasLogger;

    /**
     * In-memory storage for fallback when no persistent storage is available
     */
    private array $storage = [];

    /**
     * Counter for generating IDs in fallback mode
     */
    private int $nextId = 1;

    /**
     * Queue a log payload for later shipping (in-memory fallback)
     */
    public function enqueue(array $payload): bool
    {
        $this->storage[] = array_merge($payload, [
            'id' => $this->nextId++,
            'attempts' => 0,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        return true;
    }

    /**
     * Claim a batch of queued logs for processing (in-memory fallback)
     */
    public function claimBatch(int $limit = 100, int $minId = 0): array
    {
        $batch = [];
        foreach ($this->storage as &$item) {
            if ($item['id'] > $minId && count($batch) < $limit) {
                $item['attempts']++;
                $batch[] = $item;
            }
        }
        return $batch;
    }

    /**
     * Delete successfully processed logs (in-memory fallback)
     */
    public function deleteMany(array $ids): bool
    {
        $this->storage = array_filter($this->storage, fn($item) => !in_array($item['id'], $ids));
        return true;
    }

    /**
     * Bump retry attempts for failed logs (in-memory fallback)
     */
    public function bumpAttempts(array $ids): bool
    {
        foreach ($this->storage as &$item) {
            if (in_array($item['id'], $ids)) {
                $item['attempts']++;
            }
        }
        return true;
    }

    /**
     * Get queue stats (in-memory fallback)
     */
    public function getStats(): array
    {
        return [
            'total' => count($this->storage),
            'pending' => count(array_filter($this->storage, fn($item) => $item['attempts'] < 5)),
            'sent' => 0, // Not tracked in memory
            'failed' => count(array_filter($this->storage, fn($item) => $item['attempts'] >= 5))
        ];
    }

    /**
     * Clear all logs from the queue (in-memory fallback)
     */
    public function clearAll(): bool
    {
        $this->storage = [];
        $this->nextId = 1;
        return true;
    }

    /**
     * Purge old logs (no-op for in-memory)
     */
    public function purgeOld(int $maxAgeSeconds = 600): int
    {
        // In-memory storage doesn't implement aging
        return 0;
    }
}