import { useMutation } from '@tanstack/react-query'
import { api } from '../api'

type LoginPayload = {
  email: string
  password: string
}

export const useAuthMutation = () => {
  const login = useMutation({
    mutationFn: async (payload: LoginPayload) => {
      const response = await api.post('/auth/login', payload)
      return response.data.data
    },
    onSuccess: data => {
      // Optional: refetch 'users' list after success
      localStorage.setItem('authToken', data.token)
      localStorage.setItem('user', JSON.stringify(data.user))
    }
  })

  const logout = useMutation({
    mutationFn: async () => {
      await api.post('/auth/logout')
    },
    onSuccess: () => {
      // Optional: refetch 'users' list after success
      localStorage.removeItem('authToken')
      localStorage.removeItem('user')
    }
  })

  return { login, logout }
}
