import {
  APPLICANT_CASE_ID_SESSION_KEY,
  APPLICANT_REPORT_STEP_SESSION_KEY,
  CASE_ID_SEARCH_PARAM,
  FRESH_DASHBOARD_SEARCH_PARAM,
} from "../lib/applicantRegistrationSession";

/** True when report tab has enough content to treat the first step as done. */
export function reportDraftLooksComplete(report: Record<string, unknown> | undefined): boolean {
  if (!report || typeof report !== "object") return false;
  const initiativeName = String(report.initiativeName ?? "").trim();
  const introduction = String(report.introduction ?? "").trim();
  return initiativeName.length > 0 || introduction.length > 0;
}

/**
 * Initial case id: prefers `?caseId=` (resume from Postgres), ignores when `?fresh=1`,
 * otherwise sessionStorage.
 */
export function readInitialApplicantCaseId(): string {
  if (typeof window === "undefined") return "";
  const params = new URLSearchParams(window.location.search);
  if (params.get(FRESH_DASHBOARD_SEARCH_PARAM) === "1") return "";
  const fromUrl = params.get(CASE_ID_SEARCH_PARAM)?.trim();
  if (fromUrl) {
    try {
      sessionStorage.setItem(APPLICANT_CASE_ID_SESSION_KEY, fromUrl);
    } catch {
      /* ignore */
    }
    return fromUrl;
  }
  try {
    return sessionStorage.getItem(APPLICANT_CASE_ID_SESSION_KEY) ?? "";
  } catch {
    return "";
  }
}

export function readReportStepDoneFromSession(): boolean {
  if (typeof window === "undefined") return false;
  try {
    return sessionStorage.getItem(APPLICANT_REPORT_STEP_SESSION_KEY) === "1";
  } catch {
    return false;
  }
}

export { APPLICANT_REPORT_STEP_SESSION_KEY as REPORT_STEP_SESSION_KEY };
