import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "@xtablo/shared";
import { useAuthedApi } from "./auth";

// Invite user by email
export const useInviteUser = () => {
  const queryClient = useQueryClient();
  const api = useAuthedApi();
  const { mutate, isPending } = useMutation({
    mutationFn: async ({ email, tablo_id }: { email: string; tablo_id: string }) => {
      const { data } = await api.post(`/api/v1/tablos/invite/${tablo_id}`, {
        email,
      });
      return data;
    },
    onSuccess: (_, { tablo_id }) => {
      toast.add(
        {
          title: "Invitation envoyée avec succès",
          description: "L'utilisateur a été invité avec succès",
          type: "success",
        },
        {
          timeout: 2000,
        }
      );
      queryClient.invalidateQueries({ queryKey: ["tablo-members", tablo_id] });
      queryClient.invalidateQueries({ queryKey: ["tablo-invites", tablo_id] });
    },
  });
  return { mutate, isPending };
};

export const useJoinTablo = () => {
  const api = useAuthedApi();
  const { mutate } = useMutation<{ tablo_id: string }, unknown, { token: string }>({
    mutationFn: async ({ token }: { token: string }) => {
      const { data } = await api.post("/api/v1/tablos/join", { token });
      return data;
    },
  });
  return mutate;
};
