import { useQuery } from "react-query";
import firestore, {or, query, where} from "@react-native-firebase/firestore";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { IToDo } from "@/hooks/firebase/types/todoData";

export const useGetTodos = () => {
    const { user, profileData } = useAuthContext();

    return useQuery({
        queryKey: ["todos", user?.uid],
        queryFn: async () => {

            let snapshot;
            if (profileData?.userType === ProfileType.PARENT) {
                snapshot = await firestore()
                    .collection("Todos")
                    .where("familyId", "==", profileData?.familyId)
                    .get();
            } else {
                let todosQuery = query(firestore().collection("Todos"), or(where("assignees", "array-contains", user?.uid), where("creatorId", "==", user?.uid)));
                snapshot = await todosQuery.get();
            }

            return snapshot.docs.map((doc) => {
                const data = doc.data();

                return {
                    ...data,
                    id: doc.id,
                    date: data.date ? new Date(data.date.seconds * 1000) : null,
                    repeatDays: data.repeatDays ?? []
                };
            }) as IToDo[];
        }
    })
};