import {useMutation, useQueryClient} from "@tanstack/react-query"; import {useAuthContext} from "@/contexts/AuthContext"; import functions from "@react-native-firebase/functions"; interface SyncResponse { success: boolean; eventCount: number; message?: string; } export const useFetchAndSaveGoogleEvents = () => { const queryClient = useQueryClient(); const { profileData } = useAuthContext(); return useMutation({ mutationKey: ["fetchAndSaveGoogleEvents", "sync"], mutationFn: async ({ email }: { email?: string }) => { if (!email || !profileData?.googleAccounts?.[email]) { throw new Error("No valid Google account found"); } try { const response = await functions() .httpsCallable('triggerGoogleSync')({ email }); return response.data as SyncResponse; } catch (error: any) { console.error("Error initiating Google Calendar sync:", error); throw new Error(error.details?.message || error.message || "Failed to sync calendar"); } }, onSuccess: (data) => { queryClient.invalidateQueries({queryKey: ["events"]}); console.log(`Successfully synced ${data.eventCount} events`); } }); };