// /composables/usePermissions.ts
export const usePermission = () => {
  /**
   * Extract group and role from path
   * Example: "/Instalasi STIM/Devops/Superadmin"
   * → { group: "STIM", role: "superadmin" }
   */
  const parsePath = (path: string) => {
    const parts = path.split("/").filter(Boolean);
    const group = parts[1] || ""; // "STIM"
    const role = parts.at(-1)?.toLowerCase() || ""; // "superadmin"
    return { group, role };
  };

  /**
   * Fetch permission from backend API
   */
  const fetchPermission = async (path: string) => {
    const { group, role } = parsePath(path);
    const url = `http://10.10.123.140:8089/api/permission?roles=${role}&groups=${group}`;

    const { data, error } = await useFetch(url, {
      method: "GET",
    });

    if (error.value) {
      console.error("❌ Gagal mengambil permission:", error.value);
      throw error.value;
    }

    console.log("✅ Permission data:", data.value);
    return data.value;
  };

  return { parsePath, fetchPermission };
};
