const STORAGE_PREFIX = 'dyolink.labDispatchDefaults.';

/** Chips under lab search — last destinations this clinic actually sent a case to. */
export const MAX_RECENT_LABS = 3;

function storageKey(clinicOrganizationId: string): string {
  return `${STORAGE_PREFIX}${clinicOrganizationId}`;
}

function uniqueIds(ids: string[]): string[] {
  const out: string[] = [];
  for (const id of ids) {
    if (id && !out.includes(id)) out.push(id);
  }
  return out;
}

export function loadRecentLabIds(clinicOrganizationId: string | null | undefined): string[] {
  if (!clinicOrganizationId || typeof window === 'undefined') return [];
  try {
    const raw = window.localStorage.getItem(storageKey(clinicOrganizationId));
    if (!raw) return [];
    const parsed = JSON.parse(raw) as {
      recentLabIds?: unknown;
      lastLabId?: unknown;
    };
    const fromList = Array.isArray(parsed.recentLabIds)
      ? parsed.recentLabIds.filter((id): id is string => typeof id === 'string')
      : [];
    // Older builds stored a single lastLabId used as an auto-selected default.
    const fromLegacy = typeof parsed.lastLabId === 'string' ? [parsed.lastLabId] : [];
    return uniqueIds([...fromList, ...fromLegacy]).slice(0, MAX_RECENT_LABS);
  } catch {
    return [];
  }
}

function writeRecentLabIds(clinicOrganizationId: string, recentLabIds: string[]): void {
  if (typeof window === 'undefined') return;
  try {
    window.localStorage.setItem(
      storageKey(clinicOrganizationId),
      JSON.stringify({ recentLabIds }),
    );
  } catch {
    // Ignore quota / private-mode failures.
  }
}

/** Record a lab after a successful send — suggestion chips only, never a form default. */
export function rememberRecentLab(
  clinicOrganizationId: string | null | undefined,
  labId: string,
): void {
  if (!clinicOrganizationId || !labId) return;
  writeRecentLabIds(
    clinicOrganizationId,
    uniqueIds([labId, ...loadRecentLabIds(clinicOrganizationId)]).slice(0, MAX_RECENT_LABS),
  );
}
