import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { OrganizationRequest } from '../../types/services/organization'
import { api } from '../api'

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

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

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

  return { createOrganization, updateOrganization, deleteOrganization }
}
