/**
 * Session keys shared with `Dashboard` for in-progress registration (draft tabs).
 * Clearing these starts a fresh InitiativeReport / InitiativeApplication /
 * ContributionConfirmation / ReviewPanel flow.
 *
 * Partial port from `fe0/src/lib/applicantRegistrationSession.ts`: the constants + the
 * dependency-free helpers the data layer needs. `prepareFreshApplicantDashboardNavigation`
 * (which also clears the last-submission record via `clearApplicantSubmissionRecord`) is left
 * as a TODO(slice-N) because that record module pulls in mock data + submit/PDF code that
 * belongs to a later slice.
 */

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';

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 */
  }
}

/**
 * Resets in-progress registration so the dashboard mounts empty forms.
 *
 * Partial port of fe0's `prepareFreshApplicantDashboardNavigation`: it clears the
 * draft session storage. fe0 also calls `clearApplicantSubmissionRecord()` (the
 * last-submission record), which pulls in the mock-data / submit / PDF modules of a
 * later slice — left as a TODO(slice-N) until that record module lands in shared.
 */
export function prepareFreshApplicantDashboardNavigation(): void {
  clearApplicantRegistrationSessionStorage();
  // TODO(slice-N): also clearApplicantSubmissionRecord() once the submission-record
  // module (mock data + submit/PDF) is ported into @ump/shared.
}

/** 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 });
}
