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

export const useUpdateSubUser = () => {
    const queryClient = useQueryClient()
    const {profileType} = useAuthContext()

    return useMutation({
        mutationKey: ["updateSubUser"],
        mutationFn: async ({ userProfile }: { userProfile: Partial<UserProfile>; }) => {
            if (profileType === ProfileType.PARENT) {
                if (userProfile) {
                    console.log("Updating user data for UID:", userProfile.uid);

                    try {
                        const updatedUserData = Object.fromEntries(
                            Object.entries(userProfile).map(([key, value]) =>
                                [key, value === null ? firestore.FieldValue.delete() : value]
                            )
                        );

                        console.log("Updated user data with deletions:", updatedUserData);

                        await firestore()
                            .collection("Profiles")
                            .doc(userProfile.uid)
                            .update(updatedUserData);

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

                        console.log("Profile data updated in context.");
                    } catch (e) {
                        console.error("Error updating user data:", e);
                    }
                } else {
                    console.warn("No user found: user profile is undefined.");
                }
            } else {
                throw Error("Can't update sub-users as a non-parent.")
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries({queryKey: ["getChildrenByParentId"]})
            queryClient.invalidateQueries({queryKey: ["familyMembers"]})
        }
    });
}