const STORAGE_PREFIX = 'dyolink.labDispatchDefaults.';

export type LabDispatchDefaults = {
  lastLabId: string | null;
  lastProsthesisByLab: Record<string, string>;
};

const EMPTY: LabDispatchDefaults = {
  lastLabId: null,
  lastProsthesisByLab: {},
};

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

export function loadLabDispatchDefaults(clinicOrganizationId: string | null | undefined): LabDispatchDefaults {
  if (!clinicOrganizationId || typeof window === 'undefined') return EMPTY;
  try {
    const raw = window.localStorage.getItem(storageKey(clinicOrganizationId));
    if (!raw) return EMPTY;
    const parsed = JSON.parse(raw) as Partial<LabDispatchDefaults>;
    return {
      lastLabId: typeof parsed.lastLabId === 'string' ? parsed.lastLabId : null,
      lastProsthesisByLab:
        parsed.lastProsthesisByLab && typeof parsed.lastProsthesisByLab === 'object'
          ? parsed.lastProsthesisByLab
          : {},
    };
  } catch {
    return EMPTY;
  }
}

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

export function rememberLastLab(clinicOrganizationId: string | null | undefined, labId: string): void {
  if (!clinicOrganizationId || !labId) return;
  const current = loadLabDispatchDefaults(clinicOrganizationId);
  writeDefaults(clinicOrganizationId, { ...current, lastLabId: labId });
}

export function rememberLastProsthesisType(
  clinicOrganizationId: string | null | undefined,
  labId: string,
  prosthesisTypeCode: string,
): void {
  if (!clinicOrganizationId || !labId || !prosthesisTypeCode) return;
  const current = loadLabDispatchDefaults(clinicOrganizationId);
  writeDefaults(clinicOrganizationId, {
    ...current,
    lastLabId: labId,
    lastProsthesisByLab: {
      ...current.lastProsthesisByLab,
      [labId]: prosthesisTypeCode,
    },
  });
}

export function lastProsthesisTypeForLab(
  clinicOrganizationId: string | null | undefined,
  labId: string | null | undefined,
): string | null {
  if (!clinicOrganizationId || !labId) return null;
  return loadLabDispatchDefaults(clinicOrganizationId).lastProsthesisByLab[labId] ?? null;
}
