import { ref } from "vue";

import { api } from "../services/api";

/** @typedef {{ key?: string, permission?: string, items?: [], to?: string, path?: string, header?: boolean }} NavItem */

const menu = ref(/** @type {NavItem[]} */ ([]));
const loaded = ref(false);

/** Clears cached nav (e.g. on logout). Safe to import from `useAuth.js`. */
export function resetNavigation() {
  menu.value = [];
  loaded.value = false;
}

export function useNavigation() {
  async function fetchNavigation() {
    try {
      const { data } = await api.get("/api/navigation");
      menu.value = Array.isArray(data) ? data : [];
      loaded.value = true;
    } catch {
      menu.value = [];
      loaded.value = true;
    }
  }

  return {
    menu,
    loaded,
    fetchNavigation,
    resetNavigation,
  };
}
