'use strict';

const DEFAULT_RESTORE_ACTIVITY_SUPPRESSION_MS = 10_000;

function numericMs(value) {
  const n = Number(value || 0);
  return Number.isFinite(n) && n > 0 ? n : 0;
}

function restoreHoldMs(runningHoldMs = 0) {
  return Math.max(DEFAULT_RESTORE_ACTIVITY_SUPPRESSION_MS, numericMs(runningHoldMs));
}

function beginRestoreState(session, opts = {}) {
  if (!session) return null;
  const now = numericMs(opts.now) || Date.now();
  const until = now + restoreHoldMs(opts.runningHoldMs);
  session._restoredFromStartup = true;
  session._restoreStarting = true;
  session._restoreStartingUntil = until;
  session._restoreActivitySuppressUntil = until;
  session._restoreStartedAt = now;
  return { until };
}

function restoreStartingActive(session, now = Date.now()) {
  if (!session || !session._restoreStarting) return false;
  const until = numericMs(session._restoreStartingUntil);
  return !until || now < until;
}

function restoreActivitySuppressed(session, now = Date.now()) {
  if (!session) return false;
  const until = numericMs(session._restoreActivitySuppressUntil);
  if (!until || now >= until) return false;
  const startedAt = numericMs(session._restoreStartedAt);
  const lastUserInputAt = numericMs(session.lastUserInputAt);
  return !(lastUserInputAt && (!startedAt || lastUserInputAt >= startedAt));
}

function clearRestoreState(session) {
  if (!session) return session;
  session._restoredFromStartup = false;
  session._restoreStarting = false;
  session._restoreStartingUntil = 0;
  session._restoreActivitySuppressUntil = 0;
  session._restoreStartedAt = 0;
  return session;
}

function markUserInput(session, now = Date.now()) {
  if (!session) return session;
  session.lastUserInputAt = now;
  if (restoreStartingActive(session, now) || restoreActivitySuppressed(session, now)) {
    clearRestoreState(session);
  }
  return session;
}

module.exports = {
  DEFAULT_RESTORE_ACTIVITY_SUPPRESSION_MS,
  beginRestoreState,
  clearRestoreState,
  markUserInput,
  restoreActivitySuppressed,
  restoreHoldMs,
  restoreStartingActive,
};
