"use client";

import { ClientMenu } from "@/types/mutual/context/validations";
import { API_BASE_URL } from "@/config/config";
import { createContextHook } from "../hookFactory";

// Original fetch functions for backward compatibility
async function checkContextPageMenu() {
  const result = await fetch(`${API_BASE_URL}/context/page/menu`, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
  });
  try {
    const data = await result.json();
    if (data.status == 200) return data.data;
  } catch (error) {
    throw new Error("No data is found");
  }
}

async function setContextPageMenu(setMenu: ClientMenu) {
  const result = await fetch(`${API_BASE_URL}/context/page/menu`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(setMenu),
  });
  try {
    const data = await result.json();
    return data;
  } catch (error) {
    throw new Error("No data is set");
  }
}

// Create the menu hook using the factory
const useContextMenu = createContextHook<ClientMenu>({
  endpoint: "/context/page/menu",
  contextName: "menu",
  extractAvailableItems: (data) => data.selectionList || [],
  enablePeriodicRefresh: false,
});

// Custom hook for menu data with the expected interface
interface UseMenuResult {
  menuData: ClientMenu | null;
  availableApplications: string[];
  isLoading: boolean;
  error: string | null;
  refreshMenu: () => Promise<void>;
  updateMenu: (newMenu: ClientMenu) => Promise<boolean>;
}

// Wrapper hook that adapts the generic hook to the expected interface
export function useMenu(): UseMenuResult {
  const { data, availableItems, isLoading, error, refresh, update } =
    useContextMenu();

  return {
    menuData: data,
    availableApplications: availableItems,
    isLoading,
    error,
    refreshMenu: refresh,
    updateMenu: update,
  };
}

export { checkContextPageMenu, setContextPageMenu };
