"use strict";

const EVIDENCE_MAINTENANCE_TTL_MS = 15 * 1000;

let evidenceMaintenanceSession = null;

function startEvidenceMaintenanceSession(source) {
  evidenceMaintenanceSession = buildEvidenceMaintenanceSession(source);

  return getEvidenceMaintenanceStatus();
}

function refreshEvidenceMaintenanceSession(source) {
  evidenceMaintenanceSession = buildEvidenceMaintenanceSession(source);

  return getEvidenceMaintenanceStatus();
}

function endEvidenceMaintenanceSession(source) {
  cleanupExpiredEvidenceMaintenanceSession();

  if (
    evidenceMaintenanceSession &&
    evidenceMaintenanceSession.source === normalizeMaintenanceSource(source)
  ) {
    evidenceMaintenanceSession = null;
  }

  return getEvidenceMaintenanceStatus();
}

function isEvidenceWriteSuspended() {
  cleanupExpiredEvidenceMaintenanceSession();

  return evidenceMaintenanceSession !== null;
}

function getEvidenceMaintenanceStatus() {
  cleanupExpiredEvidenceMaintenanceSession();

  if (!evidenceMaintenanceSession) {
    return {
      success: true,
      evidenceWriteSuspended: false,
      source: null,
      lastHeartbeatAt: null,
      expiresAt: null
    };
  }

  return {
    success: true,
    evidenceWriteSuspended: true,
    source: evidenceMaintenanceSession.source,
    lastHeartbeatAt: evidenceMaintenanceSession.lastHeartbeatAt,
    expiresAt: evidenceMaintenanceSession.expiresAt
  };
}

function buildEvidenceMaintenanceSession(source) {
  const now = Date.now();
  const lastHeartbeatAt = new Date(now).toISOString();
  const expiresAt = new Date(now + EVIDENCE_MAINTENANCE_TTL_MS).toISOString();

  return {
    source: normalizeMaintenanceSource(source),
    lastHeartbeatAt: lastHeartbeatAt,
    expiresAt: expiresAt
  };
}

function cleanupExpiredEvidenceMaintenanceSession() {
  if (!evidenceMaintenanceSession) {
    return;
  }

  const expiresAt = Date.parse(evidenceMaintenanceSession.expiresAt);

  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
    evidenceMaintenanceSession = null;
  }
}

function normalizeMaintenanceSource(source) {
  return typeof source === "string" && source.trim()
    ? source.trim()
    : "unknown";
}
