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

/** Invitations addressed to the signed-in user's email. */
export function useMyInvitations() {
  return useQuery({
    queryKey: ['invitations'],
    queryFn: () => apiClient.listMyInvitations(),
    meta: { toastOnError: true },
  });
}

/**
 * Accept a pending invitation, then refresh both the networks list (the user
 * is now a member) and the invitations list (the invite is consumed).
 */
export function useAcceptInvitation() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (networkId: string) =>
      apiClient.acceptInvitation({ network_id: networkId }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['networks'] });
      void queryClient.invalidateQueries({ queryKey: ['invitations'] });
    },
  });
}

/** Create a network; the creator becomes its admin and first member. */
export function useCreateNetwork() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateNetworkRequest) => apiClient.createNetwork(data),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['networks'] });
    },
  });
}
