import { useMutation, useQuery } from '@apollo/client'
import { LOGIN, LOGOUT } from '../mutations'
import { GET_ME } from '../queries'
import { setAuthToken, removeAuthToken } from '@/lib/auth-storage'

export function useLogin() {
  const [mutate, { loading, error }] = useMutation(LOGIN, {
    onCompleted: (data) => {
      if (data?.login?.token) {
        setAuthToken(data.login.token)
      }
    },
  })

  return {
    login: (email: string, password: string) =>
      mutate({ variables: { email, password } }),
    loading,
    error,
  }
}

export function useLogout() {
  const [mutate, { loading, error }] = useMutation(LOGOUT, {
    onCompleted: () => {
      removeAuthToken()
      // Optionally redirect to login page
      if (typeof window !== 'undefined') {
        window.location.href = '/login'
      }
    },
  })

  return {
    logout: () => mutate(),
    loading,
    error,
  }
}

export function useMe() {
  return useQuery(GET_ME, {
    fetchPolicy: 'cache-and-network',
  })
}

