/**
 * Persists B2CDataTable UI state per user in Laravel (`user_table_states`).
 * Legacy `maestro-table-state-*` keys are cleared when the server has no row so
 * a reset cannot be undone by re-uploading stale local data.
 */

import { api, ensureCsrf } from "./api.js";

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

function legacyLocalKey(tableKey) {
  return LEGACY_PREFIX + encodeURIComponent(tableKey);
}

export const tableStateService = {
  /**
   * @returns {Promise<{ data?: { state: object|null } }>}
   */
  async get(tableKey) {
    try {
      await ensureCsrf();
      const encoded = encodeURIComponent(tableKey);
      const { data } = await api.get(`/api/user/table-states/${encoded}`);
      const state = data?.state ?? null;
      if (state == null && typeof localStorage !== "undefined") {
        localStorage.removeItem(legacyLocalKey(tableKey));
      }
      return { data: { state } };
    } catch {
      return { data: { state: null } };
    }
  },

  /**
   * @param {string} tableKey
   * @param {object} state
   * @param {import('axios').AxiosRequestConfig} [_opts]
   */
  async put(tableKey, state, _opts = {}) {
    await ensureCsrf();
    const encoded = encodeURIComponent(tableKey);
    await api.put(
      `/api/user/table-states/${encoded}`,
      { state: state ?? {} },
      _opts,
    );
    return { data: { ok: true } };
  },

  async delete(tableKey) {
    await ensureCsrf();
    const encoded = encodeURIComponent(tableKey);
    await api.delete(`/api/user/table-states/${encoded}`);
    return { data: { ok: true } };
  },
};
