import { createContext, FunctionComponent } from 'react'
import {
  CurrentUserQuery,
  useCurrentUserQuery,
  useUserLogoutMutation,
  useUserLoginMutation,
  CurrentUserDocument
} from '../gql'

interface IUserContext {
  user?: ReturnType<typeof useCurrentUserQuery>
  login?: ReturnType<typeof useUserLoginMutation>
  logout?: ReturnType<typeof useUserLogoutMutation>
}

export const UserContext = createContext<IUserContext>({})

export const UserProvider: FunctionComponent = ({ children }) => {
  const user = useCurrentUserQuery({ fetchPolicy: 'network-only' })
  const logout = useUserLogoutMutation({
    refetchQueries: [{ query: CurrentUserDocument }]
  })
  const login = useUserLoginMutation({
    refetchQueries: [{ query: CurrentUserDocument }]
  })
  console.log('current user', user.data)
  return (
    <UserContext.Provider value={{ user, login, logout }}>
      {children}
    </UserContext.Provider>
  )
}
