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

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

    return useMutation({
        mutationKey: ["fetchAndSaveAppleEvents", "sync"],
        mutationFn: async ({token, email, date}: { token?: string; email?: string, date?: Date }) => {
            const baseDate = date || new Date();
            const timeMin = new Date(new Date(baseDate).setFullYear(new Date(baseDate).getMonth() - 1));
            const timeMax = new Date(new Date(baseDate).setFullYear(new Date(baseDate).getMonth() + 1));

            try {
                const response = await fetchiPhoneCalendarEvents(
                    profileData?.familyId!,
                    email,
                    timeMin,
                    timeMax
                );

                console.log(response);
                const items = response ?? [];
                await createEventsFromProvider(items);
            } catch (error) {
                console.error("Error fetching and saving Apple Calendar events: ", error);
                throw error;
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries(["events"])
        },
    });
};