import {useMutation, useQueryClient} from "react-query";
import {fetchGoogleCalendarEvents} from "@/calendar-integration/google-calendar-utils";
import {useAuthContext} from "@/contexts/AuthContext";
import {useCreateEventsFromProvider} from "@/hooks/firebase/useCreateEvent";
import {useClearTokens} from "@/hooks/firebase/useClearTokens";

export const useFetchAndSaveGoogleEvents = () => {
    const queryClient = useQueryClient()
    const {profileData} = useAuthContext();
    const {mutateAsync: createEventsFromProvider} = useCreateEventsFromProvider();
    const {mutateAsync: clearToken} = useClearTokens();

    return useMutation({
        mutationKey: ["fetchAndSaveGoogleEvents"],
        mutationFn: async ({token, email}: { token?: string; email?: string }) => {
            console.log("Fetching Google Calendar events...");
            const timeMin = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
            const timeMax = new Date(new Date().setFullYear(new Date().getFullYear() + 5));

            console.log("Token: ", token);

            try {
                const response = await fetchGoogleCalendarEvents(
                    token,
                    email,
                    profileData?.familyId,
                    timeMin.toISOString().slice(0, -5) + "Z",
                    timeMax.toISOString().slice(0, -5) + "Z"
                );

                if(!response.success) {
                    await clearToken({email: email!, provider: "google"})
                    return
                }

                console.log("Google Calendar events fetched:", response);

                const items = response?.googleEvents?.map((item) => {
                    if (item.allDay) {
                        item.startDate = new Date(new Date(item.startDate).setHours(0, 0, 0, 0));
                        item.endDate = item.startDate;
                    }
                    return item;
                }) || [];

                await createEventsFromProvider(items);
            } catch (error) {
                console.error("Error fetching Google Calendar events:", error);
                throw error; // Ensure errors are propagated to the mutation
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries(["events"])
        },
    });
};