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

/** Pending invitations sent for a network (member-visible). */
export function useNetworkInvitations(networkId: string) {
  return useQuery({
    queryKey: ['network-invitations', networkId],
    queryFn: () => apiClient.listNetworkInvitations(networkId),
  });
}

/**
 * Invite people by email. Existing users join directly; others get a pending
 * invitation. Refreshes both the network (new members) and its invitation list.
 */
export function useAddMembers(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (emails: string[]) =>
      apiClient.addMembers(networkId, { email_addresses: emails }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['networks'] });
      void queryClient.invalidateQueries({
        queryKey: ['network-invitations', networkId],
      });
    },
  });
}

/** Remove a member from the network (admin only). */
export function useRemoveMember(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (humanId: string) => apiClient.removeMember(networkId, humanId),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['networks'] });
    },
  });
}

/** Revoke a pending invitation by email. */
export function useRevokeInvitation(networkId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (email: string) =>
      apiClient.revokeInvitation(networkId, { email }),
    onSuccess: () => {
      void queryClient.invalidateQueries({
        queryKey: ['network-invitations', networkId],
      });
    },
  });
}
