import { ref } from "vue";
import apiClient from "../services/api.js";

/**
 * Backend-driven navigation (filtered by Spatie permissions).
 * Fetched after auth; layout uses menu for main sidebar and subsidebar (tree includes companies children when currentPath is under a company).
 */
const menu = ref([]);
const loaded = ref(false);

export function useNavigation() {
  /**
   * Fetch navigation from GET /api/navigation.
   * @param {string} [currentPath] - Current route path; when under /companies/:id/..., backend hydrates companies.children so subsidebar shows.
   */
  async function fetchNavigation(currentPath) {
    try {
      const params = currentPath ? { currentPath } : {};
      const { data } = await apiClient.get("/navigation", { params });
      if (Array.isArray(data)) {
        menu.value = data;
      } else if (data && typeof data === "object" && data.tree) {
        menu.value = data.tree;
      } else {
        menu.value = [];
      }
      loaded.value = true;
    } catch {
      menu.value = [];
      loaded.value = true;
    }
  }

  function resetNavigation() {
    menu.value = [];
    loaded.value = false;
  }

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