/**
 * Session keys shared with `Dashboard` for in-progress registration (draft tabs).
 * Clearing these starts a fresh InitiativeReport / InitiativeApplication /
 * ContributionConfirmation / ReviewPanel flow.
 */
import { clearApplicantSubmissionRecord } from "@/lib/applicantSubmissionRecord";

export const APPLICANT_CASE_ID_SESSION_KEY = "applicant-case-id";
export const APPLICANT_REPORT_STEP_SESSION_KEY = "applicant-report-tiep-theo-done";

/** Query flag consumed by `Dashboard` to reset React state (see `?fresh=1`). */
export const FRESH_DASHBOARD_SEARCH_PARAM = "fresh";

/** Load existing draft from Postgres via `GET /api/v1/application-drafts/:caseId` (see `?caseId=…`). */
export const CASE_ID_SEARCH_PARAM = "caseId";
const DASHBOARD_PATH = "/dashboard";
const APPLICANT_DRAFT_SNAPSHOT_KEY = "initiativeDraft.v1";

function buildDashboardHref(params?: Record<string, string>): string {
  if (!params || Object.keys(params).length === 0) return DASHBOARD_PATH;
  const query = new URLSearchParams(params);
  return `${DASHBOARD_PATH}?${query.toString()}`;
}

/** Clears draft case id and report-tab gate so dashboard forms mount empty. */
export function clearApplicantRegistrationSessionStorage(): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.removeItem(APPLICANT_CASE_ID_SESSION_KEY);
    sessionStorage.removeItem(APPLICANT_REPORT_STEP_SESSION_KEY);
  } catch {
    /* ignore */
  }
}

/** Clears session + last-submission shortcut before navigating to a new registration. */
export function prepareFreshApplicantDashboardNavigation(): void {
  clearApplicantRegistrationSessionStorage();
  clearApplicantSubmissionRecord();
  if (typeof window !== "undefined") {
    try {
      localStorage.removeItem(APPLICANT_DRAFT_SNAPSHOT_KEY);
    } catch {
      /* ignore */
    }
  }
}

/** Full URL for dashboard with `fresh` flag (hard navigation recommended). */
export function getFreshApplicantDashboardHref(): string {
  return buildDashboardHref({ [FRESH_DASHBOARD_SEARCH_PARAM]: "1" });
}

/** Resume in-progress registration from server-backed draft (PostgreSQL). */
export function getResumeApplicantDashboardHref(caseId: string): string {
  const id = caseId.trim();
  if (!id) return DASHBOARD_PATH;
  return buildDashboardHref({ [CASE_ID_SEARCH_PARAM]: id });
}
