const STORAGE_KEY = 'process-management-selection';

export interface ProcessSelectionState {
  level1Id: number | null;
  methodId: number | null;
}

export function readProcessSelection(): ProcessSelectionState {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) {
      return { level1Id: null, methodId: null };
    }
    const parsed = JSON.parse(raw) as Partial<ProcessSelectionState>;
    return {
      level1Id:
        parsed.level1Id != null && Number.isFinite(Number(parsed.level1Id))
          ? Number(parsed.level1Id)
          : null,
      methodId:
        parsed.methodId != null && Number.isFinite(Number(parsed.methodId))
          ? Number(parsed.methodId)
          : null,
    };
  } catch {
    return { level1Id: null, methodId: null };
  }
}

export function writeProcessSelection(state: ProcessSelectionState) {
  localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify({
      level1Id: state.level1Id,
      methodId: state.methodId,
    }),
  );
}
