import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { api } from '../api'
import { AccountRequest } from '../queries/chartOfAccountType'

export const useAccountsMutation = () => {
  const queryClient = useQueryClient()

  const createAccount = useMutation({
    mutationFn: async (newAccount: AccountRequest) => {
      const response = await api.post('/accounts', newAccount)
      return response.data
    },
    onSuccess: () => {
      toast.success('Account created successfully!')
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
    }
  })

  const updateAccount = useMutation({
    mutationFn: async ({ id, payload }: { id: string; payload: AccountRequest }) => {
      const response = await api.put(`/accounts/${id}`, payload)
      return response.data
    },
    onSuccess: () => {
      toast.success('Account updated successfully!')
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
    }
  })

  const deleteAccount = useMutation({
    mutationFn: async (id: string) => {
      const response = await api.delete(`/accounts/${id}`)
      return response.data
    },
    onSuccess: () => {
      toast.success('Account deleted successfully!')
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
    }
  })

  return { createAccount, updateAccount, deleteAccount }
}
