import { useQuery } from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";
import { useAuthContext } from "@/contexts/AuthContext";

interface FirestoreTimestamp {
    seconds: number;
    nanoseconds: number;
}

interface NotificationFirestore {
    creatorId: string;
    familyId: string;
    content: string;
    eventId: string;
    timestamp: FirestoreTimestamp;
    date?: FirestoreTimestamp;
}

export interface Notification {
    id: string;
    creatorId: string;
    familyId: string;
    content: string;
    eventId: string;
    timestamp: Date;
    date?: Date;
}

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

    console.log(profileData?.familyId)

    return useQuery<Notification[], Error>({
        queryKey: ["notifications", user?.uid],
        queryFn: async () => {
            const snapshot = await firestore()
                .collection("Notifications")
                .where("familyId", "==", profileData?.familyId)
                .orderBy("timestamp", "desc")
                .get();

            return snapshot.docs.map((doc) => {
                const data = doc.data() as NotificationFirestore;
                return {
                    id: doc.id,
                    ...data,
                    timestamp: new Date(data.timestamp.seconds * 1000 + data.timestamp.nanoseconds / 1e6),
                    date: data.date ? new Date(data.date.seconds * 1000 + data.date.nanoseconds / 1e6) : undefined,
                };
            });
        },
        refetchOnWindowFocus: true,
        staleTime: Infinity,
        gcTime: Infinity,
        placeholderData: (previousData) => previousData,
    });
};