/**
 * Pending snap + ORAC observations for executor flow: answers stay in sessionStorage
 * until the user submits from the assessment detail page.
 */
const STORAGE_KEY = 'risk_executor_snap_obs_v1';

function readRaw() {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const data = JSON.parse(raw);
    return data && typeof data === 'object' ? data : null;
  } catch {
    return null;
  }
}

/** @returns {object | null} pending payload with observations array */
export function getPendingSnapForAssessment(assessmentId) {
  const id = Number(assessmentId);
  if (!Number.isInteger(id) || id <= 0) return null;
  const data = readRaw();
  if (!data || Number(data.assessment_id) !== id) return null;
  if (!Array.isArray(data.observations) || data.observations.length === 0) return null;
  return data;
}

/** @param {object} payload - assessment_id, markedImageDataUrl, marksJson, violationTime, observations, formId, etc. */
export function setPendingSnap(payload) {
  const body = {
    version: 1,
    ...payload,
    savedAt: new Date().toISOString()
  };
  try {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(body));
    return { ok: true };
  } catch (e) {
    const name = e?.name || '';
    const msg = e?.message || '';
    const quota =
      name === 'QuotaExceededError' ||
      /quota|storage is full|exceeded/i.test(msg);
    return {
      ok: false,
      message: quota
        ? 'Browser storage is full. Try fewer queued observations, a smaller marked image, or clear site data for this app.'
        : msg || 'Could not save to browser cache.'
    };
  }
}

export function clearPendingSnap() {
  try {
    sessionStorage.removeItem(STORAGE_KEY);
  } catch {
    /* ignore */
  }
}

export function hasPendingSnapForAssessment(assessmentId) {
  return getPendingSnapForAssessment(assessmentId) != null;
}
