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

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

    return useMutation({
        mutationKey: ["fetchAndSaveOutlookEvents"],
        mutationFn: async ({token, email}: { token?: string; email?: string }) => {
            const timeMin = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
            const timeMax = new Date(new Date().setFullYear(new Date().getFullYear() + 3));

            console.log("Token: ", token ?? profileData?.microsoftToken);

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

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