import { createContext, useContext, type ReactNode } from 'react'
import type { AxiosInstance } from 'axios'
import { setApiInstance } from '@/services/api'

interface VaultContextValue {
  /** Fetch all users for the grant picker — provided by host */
  getUsers: () => Promise<Array<{ id: string; full_name: string; email: string; role: string }>>
  /** Mount path prefix used by the host's router */
  basePath: string
}

const VaultContext = createContext<VaultContextValue | null>(null)

export interface VaultProviderProps {
  /** Host's configured axios instance (shares auth headers + interceptors) */
  api: AxiosInstance
  /** Function to fetch all users — delegates to host's existing user service */
  getUsers: VaultContextValue['getUsers']
  /** Base path the host mounts vault routes at. Default: '/vault' */
  basePath?: string
  children: ReactNode
}

/**
 * VaultProvider must wrap the vault UI.
 * The host passes its own axios instance so vault-client shares
 * auth, base URL, and token refresh — no duplicate auth code.
 */
export function VaultProvider({
  api,
  getUsers,
  basePath = '/vault',
  children,
}: VaultProviderProps) {
  // Register the host's axios instance with our API module
  setApiInstance(api)

  return (
    <VaultContext.Provider value={{ getUsers, basePath }}>
      {children}
    </VaultContext.Provider>
  )
}

export function useVaultContext() {
  const ctx = useContext(VaultContext)
  if (!ctx) throw new Error('useVaultContext must be used inside <VaultProvider>')
  return ctx
}
