import {useAuthContext} from "@/contexts/AuthContext";
import {useMutation} from "react-query";
import firestore from "@react-native-firebase/firestore";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";
import {FirebaseAuthTypes} from "@react-native-firebase/auth";

export const useEditFamily = () => {
    const {user: currentUser, setProfileData} = useAuthContext()

    return useMutation({
        mutationKey: ["editFamily"],
        mutationFn: async ({newUserData, customUser}: {newUserData: Partial<UserProfile>, customUser?:  FirebaseAuthTypes.User }) => {
            const user = currentUser ?? customUser

            if (user) {
                try {
                    await firestore()
                        .collection("Families")
                        .doc(user.uid)
                        .set(newUserData);

                    const profileData = await firestore().collection("Profiles").doc(user?.uid!).get()
                    setProfileData(profileData.data() as UserProfile)
                } catch (e) {
                    console.error(e)
                }
            }
        }
    })
}