/**
 * Persists B2CDataTable UI state per user in Laravel (`user_table_states`).
 * Migrates legacy localStorage entries once when server has no row.
 */

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

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

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

async function migrateLegacyIfNeeded(tableKey, encoded) {
  if (typeof localStorage === "undefined") {
    return null;
  }
  const raw = localStorage.getItem(legacyLocalKey(tableKey));
  if (!raw) {
    return null;
  }
  try {
    const parsed = JSON.parse(raw);
    await ensureCsrf();
    await api.put(`/api/user/table-states/${encoded}`, { state: parsed });
    localStorage.removeItem(legacyLocalKey(tableKey));
    return parsed;
  } catch {
    return null;
  }
}

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}`);
      let state = data?.state ?? null;
      if (state == null) {
        const migrated = await migrateLegacyIfNeeded(tableKey, encoded);
        if (migrated != null) {
          state = migrated;
        }
      }
      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 } };
  },
};
