<?php
if (!defined('ABSPATH'))
  exit; // Exit if accessed directly

use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Queue as JobQueue;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Runner as JobRunner;

$route = new Action_Wear_Api_Route("/get_sync_health");
$route->setMethods("GET");
$route->setCallback(function () {
  $response = new ApiResponse();

  // Runner health
  $isLocked = JobRunner::isLocked();
  $heartbeat = JobRunner::getLastHeartbeat();
  $heartbeatAge = $heartbeat ? (time() - $heartbeat) : null;
  $isStale = JobRunner::isStale();
  $lastCrash = get_option('_ACTIONWEAR_LAST_BG_CRASH', null);

  $hasPending = JobQueue::hasPendingJobs();

  $runnerHealth = 'idle';
  if ($isLocked) {
    $runnerHealth = $isStale ? 'stalled' : 'running';
  } elseif ($hasPending) {
    $runnerHealth = 'waiting';
  }

  // Job counts by type
  $jobCounts = JobQueue::getJobCounts();

  // Raw lock value for debugging
  $lockValue = get_option(JobRunner::RUNNER_LOCK_KEY, null);

  $data = [
    'runner' => [
      'health' => $runnerHealth,
      'locked' => $isLocked,
      'last_heartbeat' => $heartbeat,
      'heartbeat_age_seconds' => $heartbeatAge,
      'lock_value' => $lockValue,
      'stale_threshold' => JobRunner::STALE_THRESHOLD,
    ],
    'jobs' => $jobCounts,
    'global' => [
      'last_cron_sync' => get_option('_ACTIONWEAR_LAST_SYNC', null),
      'last_bulk_price_sync' => get_option('_ACTIONWEAR_LAST_BULK_PRICE_SYNC_COMPLETED', null),
      'last_bulk_quantity_sync' => get_option('_ACTIONWEAR_LAST_BULK_QUANTITY_SYNC_COMPLETED', null),
      'bg_time_limit' => (int) get_option('_ACTIONWEAR_BG_TIME_LIMIT', 0) ?: max(10, (int) ini_get('max_execution_time') - 5) ?: 20,
      'max_execution_time' => (int) ini_get('max_execution_time'),
    ],
    'last_crash' => $lastCrash,
    'server_time' => time(),
  ];

  $response->success($data);
  return $response->getResponse();
});
$route->registerRoute();
