"use client";

import { createContext, useContext, useMemo } from 'react';
import type { DataProvider } from './data-provider';

const DataProviderContext = createContext<DataProvider | null>(null);

export function useDataProvider(): DataProvider {
  const ctx = useContext(DataProviderContext);
  if (!ctx) {
    throw new Error('useDataProvider must be used within a DataProviderProvider');
  }
  return ctx;
}

/** Returns a function that prefixes query keys with the current provider's basePath. */
export function useQueryKeyPrefix(): (...key: unknown[]) => unknown[] {
  const { basePath } = useDataProvider();
  return useMemo(() => (...key: unknown[]) => [basePath, ...key], [basePath]);
}

export function DataProviderProvider({
  value,
  children,
}: {
  value: DataProvider;
  children: React.ReactNode;
}) {
  return (
    <DataProviderContext.Provider value={value}>
      {children}
    </DataProviderContext.Provider>
  );
}
