import { createContext, FunctionComponent } from 'react'
import {
  useCurrentUserQuery,
  useUserLogoutMutation,
  useUserLoginMutation,
  CurrentUserDocument,
  TrainingsDocument,
  CurrentUserQuery,
} from '../gql'
import { ApolloError } from '@apollo/client'

interface IUserContext {
  user?: { data: CurrentUserQuery | undefined; error: ApolloError | undefined; loading: boolean }
  login?: ReturnType<typeof useUserLoginMutation>
  logout?: ReturnType<typeof useUserLogoutMutation>
}

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

export const UserProvider: FunctionComponent = ({ children }) => {
  const { data, error, loading } = useCurrentUserQuery()
  const logout = useUserLogoutMutation({
    refetchQueries: [{ query: CurrentUserDocument }, { query: TrainingsDocument }],
  })
  const login = useUserLoginMutation({
    refetchQueries: [{ query: CurrentUserDocument }, { query: TrainingsDocument }],
  })
  return (
    <UserContext.Provider value={{ user: { data, error, loading }, login, logout }}>
      {children}
    </UserContext.Provider>
  )
}
