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 useUpdateUserData = () => {
    const {user: currentUser, setProfileData} = useAuthContext()

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

            if (user) {
                try {
                    await firestore()
                        .collection("Profiles")
                        .doc(user.uid)
                        .update(newUserData);

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