'use client';

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

// Original fetch functions for backward compatibility
async function checkContextPageConfig(): Promise<ClientPageConfig | null> {
  try {
    const result = await fetch(`${API_BASE_URL}/context/page/config`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
    const data = await result.json();
    if (data.status === 200) return data.data;
    return data;
  } catch (error) {
    console.error("Error checking page config:", error);
    return null;
  }
}

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

// Create the config hook using the factory
const useContextConfig = createContextHook<ClientPageConfig>({
  endpoint: '/context/page/config',
  contextName: 'config',
  enablePeriodicRefresh: false
});

// Custom hook for config data with the expected interface
interface UseConfigResult {
  configData: ClientPageConfig | null;
  isLoading: boolean;
  error: string | null;
  refreshConfig: () => Promise<void>;
  updateConfig: (newConfig: ClientPageConfig) => Promise<boolean>;
}

// Wrapper hook that adapts the generic hook to the expected interface
export function useConfig(): UseConfigResult {
  const { data, isLoading, error, refresh, update } = useContextConfig();
  
  return {
    configData: data,
    isLoading,
    error,
    refreshConfig: refresh,
    updateConfig: update
  };
}

export { checkContextPageConfig, setContextPageConfig };
