import { VisibilityState } from "@tanstack/react-table";

const STORAGE_KEY_PREFIX = "table-column-visibility:";

const getStorageKey = (tableName: string) =>
  `${STORAGE_KEY_PREFIX}${tableName}`;

/**
 * Reads/writes column visibility per table. Backed by localStorage for now;
 * swap the implementations here for backend calls later without touching callers.
 */
export const getColumnVisibility = (
  tableName: string,
): VisibilityState | null => {
  try {
    const raw = localStorage.getItem(getStorageKey(tableName));
    return raw ? (JSON.parse(raw) as VisibilityState) : null;
  } catch {
    return null;
  }
};

export const setColumnVisibility = (
  tableName: string,
  visibility: VisibilityState,
): void => {
  try {
    localStorage.setItem(getStorageKey(tableName), JSON.stringify(visibility));
  } catch {
    // ignore write errors (e.g. storage unavailable)
  }
};
