'use client';

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

// Original fetch functions for backward compatibility
async function checkContextDashSelection() {
  try {
    const result = await fetch(`${API_BASE_URL}/context/dash/selection`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });

    const data = await result.json();
    if (data.status === 200) return data.data;
  } catch (error) {
    console.error("Error checking dash selection:", error);
  }
  return null;
}

async function setContextDashUserSelection({
  userSet,
}: {
  userSet: ClientSelection;
}) {
  try {
    const result = await fetch(`${API_BASE_URL}/context/dash/selection`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(userSet),
    });

    const data = await result.json();
    if (data.status === 200) return data.data;
  } catch (error) {
    console.error("Error setting dash selection:", error);
  }
  return null;
}

// Create the selection hook using the factory
const useContextSelection = createContextHook<ClientSelection>({
  endpoint: '/context/dash/selection',
  contextName: 'selection',
  enablePeriodicRefresh: false
});

// Custom hook for selection data with the expected interface
interface UseSelectionResult {
  selectionData: ClientSelection | null;
  isLoading: boolean;
  error: string | null;
  refreshSelection: () => Promise<void>;
  updateSelection: (newSelection: ClientSelection) => Promise<boolean>;
}

// Wrapper hook that adapts the generic hook to the expected interface
export function useSelection(): UseSelectionResult {
  const { data, isLoading, error, refresh, update } = useContextSelection();
  
  return {
    selectionData: data,
    isLoading,
    error,
    refreshSelection: refresh,
    updateSelection: update
  };
}

export { checkContextDashSelection, setContextDashUserSelection };
