import {useQuery} from "react-query";
import {ChildProfile} from "@/hooks/firebase/types/profileTypes";
import firestore from "@react-native-firebase/firestore";
import {useAuthContext} from "@/contexts/AuthContext";

export const useGetChildrenByParentId = () => {
    const {user} = useAuthContext()

    return useQuery({
            queryKey: ["getChildrenByParentId", user?.uid],
            queryFn: async (): Promise<ChildProfile[]> => {
                try {
                    const snapshot = await firestore()
                        .collection("Profiles")
                        .where("userType", "==", "child")
                        .where("parentId", "==", user?.uid!)
                        .get();

                    return snapshot.docs.map((doc) => {
                        const data = doc.data();
                        return {
                            ...data,
                            birthday: data.birthday.toDate(),
                        } as ChildProfile;
                    });
                } catch (error) {
                    console.error("Error retrieving child users:", error);
                    return [];
                }
            },
            enabled: !!user?.uid
        }
    )
}