import { useMutation, useQueryClient } from "react-query";
import functions from '@react-native-firebase/functions';
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { HttpsCallableResult } from "@firebase/functions";

export const useRemoveSubUser = () => {
  const queryClient = useQueryClient();
  const { profileType, profileData } = useAuthContext();

  return useMutation({
    mutationKey: ["removeSubUser"],
    mutationFn: async (userId: string) => {
      if (profileType === ProfileType.PARENT) {
        return await functions().httpsCallable("removeSubUser")({
          userId,
          familyId: profileData?.familyId!,
        }) as HttpsCallableResult<{ success: boolean }>;
      } else {
        throw Error("Can't remove sub-users as a non-parent.");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getChildrenByParentId"] });
      queryClient.invalidateQueries({ queryKey: ["familyMembers"] });
    },
  });
};