<?php
/**
 * Scheduler queue status.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Scheduler;

/**
 * Redacted diagnostics for queue, cron, delay, and lock health.
 */
final class QueueStatus {
	private bool $available;
	private bool $wpCronDisabled;
	private ?string $lastActivityUtc;
	private int $pending;
	private int $running;
	private int $failed;
	private int $complete;
	private int $overdue;
	private float $averageDelaySeconds;
	private int $maximumDelaySeconds;
	private int $delaySampleSize;
	private int $staleLocks;
	/**
	 * @var array<string,mixed>
	 */
	private array $repairDiagnostics;
	/**
	 * @param array<string,mixed> $repairDiagnostics Queue repair diagnostics.
	 */
	public function __construct( bool $available, bool $wpCronDisabled, ?string $lastActivityUtc, int $pending, int $running, int $failed, int $complete, int $overdue, float $averageDelaySeconds, int $maximumDelaySeconds, int $delaySampleSize, int $staleLocks, array $repairDiagnostics = array() ) {
		$this->available           = $available;
		$this->wpCronDisabled      = $wpCronDisabled;
		$this->lastActivityUtc     = $lastActivityUtc;
		$this->pending             = $pending;
		$this->running             = $running;
		$this->failed              = $failed;
		$this->complete            = $complete;
		$this->overdue             = $overdue;
		$this->averageDelaySeconds = $averageDelaySeconds;
		$this->maximumDelaySeconds = $maximumDelaySeconds;
		$this->delaySampleSize     = $delaySampleSize;
		$this->staleLocks          = $staleLocks;
		$this->repairDiagnostics   = $repairDiagnostics;
	}

	public function healthy(): bool {
		return $this->available
			&& 0 === $this->failed
			&& 0 === $this->overdue
			&& 0 === $this->staleLocks
			&& 0 === (int) ( $this->repairDiagnostics['orphaned_action_count'] ?? 0 )
			&& 0 === (int) ( $this->repairDiagnostics['missing_action_count'] ?? 0 )
			&& 0 === (int) ( $this->repairDiagnostics['mismatched_pointer_count'] ?? 0 )
			&& 0 === (int) ( $this->repairDiagnostics['lifecycle_inconsistency_count'] ?? 0 );
	}

	/**
	 * @return array<string,mixed>
	 */
	public function toArray(): array {
		return array(
			'available'             => $this->available,
			'healthy'               => $this->healthy(),
			'wp_cron_disabled'      => $this->wpCronDisabled,
			'last_activity_utc'     => $this->lastActivityUtc,
			'pending'               => $this->pending,
			'running'               => $this->running,
			'failed'                => $this->failed,
			'complete'              => $this->complete,
			'overdue'               => $this->overdue,
			'average_delay_seconds' => $this->averageDelaySeconds,
			'maximum_delay_seconds' => $this->maximumDelaySeconds,
			'delay_sample_size'     => $this->delaySampleSize,
			'stale_locks'           => $this->staleLocks,
			'repair_diagnostics'    => $this->repairDiagnostics,
		);
	}
}
