<?php

declare(strict_types=1);

namespace App\Framework\Queue;

use App\Framework\Queue\ValueObjects\JobPayload;

/**
 * In-Memory Queue Implementation
 *
 * Simple queue implementation for testing purposes
 */
final class InMemoryQueue implements Queue
{
    /** @var array<JobPayload> */
    private array $items = [];

    public function push(JobPayload $payload): void
    {
        $this->items[] = $payload;

        // Sort by priority (higher priority first)
        usort($this->items, function (JobPayload $a, JobPayload $b): int {
            return $b->priority->value <=> $a->priority->value;
        });
    }

    public function pop(): ?JobPayload
    {
        if (empty($this->items)) {
            return null;
        }

        return array_shift($this->items);
    }

    public function peek(): ?JobPayload
    {
        if (empty($this->items)) {
            return null;
        }

        return $this->items[0];
    }

    public function size(): int
    {
        return count($this->items);
    }

    public function clear(): int
    {
        $count = count($this->items);
        $this->items = [];

        return $count;
    }

    public function getStats(): array
    {
        $priorityCounts = [];

        foreach ($this->items as $item) {
            $priority = $item->priority->toString();
            $priorityCounts[$priority] = ($priorityCounts[$priority] ?? 0) + 1;
        }

        return [
            'size' => $this->size(),
            'priority_breakdown' => $priorityCounts,
            'total_items' => count($this->items),
        ];
    }
}
