import { createContext, useContext, type ReactNode } from 'react'
import type { DataProvider } from '../types'

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

export interface DataProviderProviderProps {
  children: ReactNode
  dataProvider: DataProvider
}

/**
 * Provides a data provider for data operations throughout the app.
 *
 * @example
 * ```tsx
 * const myDataProvider: DataProvider = {
 *   getList: async (resource, params) => { ... },
 *   getOne: async (resource, params) => { ... },
 *   // ... other methods
 * }
 *
 * <DataProviderProvider dataProvider={myDataProvider}>
 *   <App />
 * </DataProviderProvider>
 * ```
 */
export function DataProviderProvider({ children, dataProvider }: DataProviderProviderProps) {
  return (
    <DataProviderContext.Provider value={dataProvider}>
      {children}
    </DataProviderContext.Provider>
  )
}

/**
 * Hook to access the data provider for data operations.
 * Must be used within a DataProviderProvider.
 *
 * @example
 * ```tsx
 * const dataProvider = useDataProvider()
 * const { data, total } = await dataProvider.getList('users', { pagination: { page: 1, perPage: 10 } })
 * ```
 */
export function useDataProvider(): DataProvider {
  const context = useContext(DataProviderContext)
  if (!context) {
    throw new Error('useDataProvider must be used within a DataProviderProvider')
  }
  return context
}
