import { resolveSectionKind, SECTION_KIND } from "./sectionTypeHelpers.js";

/** In-memory permit video files for the active browser session (keyed by permit_id). */
const permitVideoStore = new Map();

export function getStoredPermitVideo(permitId) {
  if (!permitId) return [];
  const stored = permitVideoStore.get(String(permitId));
  return Array.isArray(stored) ? [...stored] : [];
}

export function setStoredPermitVideo(permitId, files) {
  if (!permitId) return [];
  const next = [...(files || [])].filter(Boolean);
  const key = String(permitId);
  if (next.length) {
    permitVideoStore.set(key, next);
  } else {
    permitVideoStore.delete(key);
  }
  return next;
}

export function clearStoredPermitVideo(permitId) {
  if (permitId) {
    permitVideoStore.delete(String(permitId));
  }
}

export function sectionKindRequiresPermitVideo(sectionKind, { skipped = false } = {}) {
  if (skipped) return false;
  return (
    sectionKind === SECTION_KIND.GENERAL ||
    sectionKind === SECTION_KIND.RISK ||
    sectionKind === SECTION_KIND.STANDARD
  );
}

export function sectionRequiresPermitVideo(section, snapshot) {
  const skipped = snapshot?.skipChoice === "yes";
  return sectionKindRequiresPermitVideo(resolveSectionKind(section), { skipped });
}

export function findPermitVideoSectionId(orderedSections, sectionCache, cacheKeyFn) {
  for (const section of orderedSections || []) {
    const snapshot = sectionCache?.[cacheKeyFn(section.section_id)];
    if (sectionRequiresPermitVideo(section, snapshot)) {
      return section.section_id;
    }
  }
  return null;
}

export function formRequiresPermitVideo(
  orderedSections,
  sectionCache,
  cacheKeyFn,
  currentSection,
  currentSkipChoice
) {
  return (orderedSections || []).some((section) => {
    const snapshot =
      section.section_id === currentSection?.section_id
        ? { skipChoice: currentSkipChoice }
        : sectionCache?.[cacheKeyFn(section.section_id)];
    return sectionRequiresPermitVideo(section, snapshot);
  });
}
