import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient } from "@/api/client";

export function useMyInvitations() {
  return useQuery({
    queryKey: ["my-invitations"],
    queryFn: () => apiClient.listMyInvitations(),
    refetchInterval: 10_000,
  });
}

export function useNetworkInvitations(networkId: string) {
  return useQuery({
    queryKey: ["network-invitations", networkId],
    queryFn: () => apiClient.listNetworkInvitations(networkId),
  });
}

export function useInviteMembers(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (emailAddresses: string[]) =>
      apiClient.addMembers(networkId, { email_addresses: emailAddresses }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["network-invitations", networkId] });
      queryClient.invalidateQueries({ queryKey: ["networks"] });
    },
  });
}

export function useAcceptInvitation() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (networkId: string) =>
      apiClient.acceptInvitation({ network_id: networkId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["my-invitations"] });
      queryClient.invalidateQueries({ queryKey: ["networks"] });
    },
  });
}

export function useRevokeInvitation(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (email: string) =>
      apiClient.revokeInvitation(networkId, { email }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["network-invitations", networkId] });
    },
  });
}

export function useRemoveMember(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (humanId: string) => apiClient.removeMember(networkId, humanId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["networks"] });
    },
  });
}
