/**
 * Persists B2CDataTable UI state locally (PrimeVue parity with TLP; no Laravel endpoint required).
 */

const PREFIX = "maestro-table-state-";

function key(tableKey) {
  return PREFIX + encodeURIComponent(tableKey);
}

export const tableStateService = {
  /**
   * @returns {Promise<{ data?: { state: object|null } }>}
   */
  async get(tableKey) {
    try {
      const raw = typeof localStorage !== "undefined"
        ? localStorage.getItem(key(tableKey))
        : null;
      const state = raw ? JSON.parse(raw) : null;

      return { data: { state } };
    } catch {
      return { data: { state: null } };
    }
  },

  /**
   * @param {string} tableKey
   * @param {object} state
   */
  async put(tableKey, state, _opts = {}) {
    try {
      if (typeof localStorage !== "undefined") {
        localStorage.setItem(key(tableKey), JSON.stringify(state ?? {}));
      }
    } catch {
      /* quota / private mode */
    }

    return { data: { ok: true } };
  },

  async delete(tableKey) {
    try {
      if (typeof localStorage !== "undefined") {
        localStorage.removeItem(key(tableKey));
      }
    } catch {
      /* ignore */
    }

    return { data: { ok: true } };
  },
};
