import {useAuthContext} from "@/contexts/AuthContext";
import {useMutation, useQueryClient} 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, refreshProfileData} = useAuthContext();
    const queryClient = useQueryClient()

    return useMutation({
        mutationKey: ["updateUserData"],
        mutationFn: async ({newUserData, customUser}: {newUserData: Partial<UserProfile>, customUser?: FirebaseAuthTypes.User }) => {
            console.log("Mutation function called with data:", { newUserData, customUser });

            const user = currentUser ?? customUser;

            if (user) {
                console.log("Updating user data for UID:", user.uid);
                try {
                    console.log("New user data:", newUserData);

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

                    console.log("User data updated successfully, fetching updated profile...");

                    await refreshProfileData()

                    console.log("Profile data updated in context.");
                } catch (e) {
                    console.error("Error updating user data:", e);
                }
            } else {
                console.warn("No user found: currentUser and customUser are both undefined.");
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries("events")
        }
    });
};
