import { useQuery, useMutation, useSubscription } from '@apollo/client'
import { GET_RESOURCES, GET_RESOURCE, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE } from '../queries'
import { CREATE_RESOURCE as CREATE_RESOURCE_MUTATION, UPDATE_RESOURCE as UPDATE_RESOURCE_MUTATION, DELETE_RESOURCE as DELETE_RESOURCE_MUTATION } from '../mutations'

export function useResources(filter?: { type?: string; status?: string; siteId?: string }) {
  return useQuery(GET_RESOURCES, {
    variables: { filter },
    fetchPolicy: 'cache-and-network',
  })
}

export function useResource(id: string) {
  return useQuery(GET_RESOURCE, {
    variables: { id },
    skip: !id,
  })
}

export function useCreateResource() {
  const [mutate, { loading, error }] = useMutation(CREATE_RESOURCE_MUTATION, {
    refetchQueries: [{ query: GET_RESOURCES }],
  })

  return {
    createResource: mutate,
    loading,
    error,
  }
}

export function useUpdateResource() {
  const [mutate, { loading, error }] = useMutation(UPDATE_RESOURCE_MUTATION, {
    refetchQueries: [{ query: GET_RESOURCES }],
  })

  return {
    updateResource: mutate,
    loading,
    error,
  }
}

export function useDeleteResource() {
  const [mutate, { loading, error }] = useMutation(DELETE_RESOURCE_MUTATION, {
    refetchQueries: [{ query: GET_RESOURCES }],
  })

  return {
    deleteResource: mutate,
    loading,
    error,
  }
}
