/**
 * Session Guard Polling Worker
 *
 * Fallback for environments where SSE (EventSource) is unavailable
 * (e.g. insecure HTTP contexts where Service Workers cannot run).
 *
 * Polls /get/isloggedin and /get/isExec at regular intervals and
 * posts results back to the main thread.
 */

let isRunning = false;
let loginTimer = null;
let execTimer = null;

const LOGIN_INTERVAL = 10000;  // 10 seconds
const EXEC_INTERVAL  = 30000;  // 30 seconds

async function checkLogin() {
  try {
    const res = await fetch('/get/isloggedin');
    if (res.ok) {
      const data = await res.json();
      self.postMessage({ type: 'session', data });
    } else if (res.status === 401 || res.status === 419) {
      self.postMessage({ type: 'session', data: { isloggedin: false } });
    }
  } catch (e) {
    // Network error — skip this tick silently
  }
}

async function checkExec() {
  try {
    const res = await fetch('/get/isExec');
    if (res.ok) {
      const text = await res.text();
      if (text && text.trim()) {
        self.postMessage({ type: 'exec', data: text.trim() });
      }
    }
  } catch (e) {
    // Network error — skip this tick silently
  }
}

function start() {
  if (isRunning) return;
  isRunning = true;

  // Run immediately on start
  checkLogin();
  checkExec();

  loginTimer = setInterval(checkLogin, LOGIN_INTERVAL);
  execTimer  = setInterval(checkExec, EXEC_INTERVAL);
}

function stop() {
  isRunning = false;
  if (loginTimer) { clearInterval(loginTimer); loginTimer = null; }
  if (execTimer)  { clearInterval(execTimer);  execTimer  = null; }
}

// Listen for commands from the main thread
self.onmessage = (event) => {
  const { type } = event.data || {};
  if (type === 'start') {
    start();
  } else if (type === 'stop') {
    stop();
    self.close();
  }
};

// Auto-start
start();
