export async function fetchGoogleCalendarEvents(token, email, familyId, startDate, endDate) {
    const googleEvents = [];
    let pageToken = null;

    do {
        const url = new URL(`https://www.googleapis.com/calendar/v3/calendars/primary/events`);
        url.searchParams.set('singleEvents', 'true');
        url.searchParams.set('timeMin', startDate);
        url.searchParams.set('timeMax', endDate);
        if (pageToken) url.searchParams.set('pageToken', pageToken);

        const response = await fetch(url.toString(), {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(`Error fetching events: ${data.error?.message || response.statusText}`);
        }

        data.items?.forEach((item) => {
            let isAllDay = false;
            let startDateTime, endDateTime;

            if (item.start) {
                if (item.start.dateTime) {
                    startDateTime = new Date(item.start.dateTime);
                } else if (item.start.date) {
                    startDateTime = new Date(item.start.date);
                    isAllDay = true;
                }
            }

            if (item.end) {
                if (item.end.dateTime) {
                    endDateTime = new Date(item.end.dateTime);
                } else if (item.end.date) {
                    endDateTime = new Date(item.end.date);
                    isAllDay = true;
                }
            }

            const googleEvent = {
                id: item.id,
                title: item.summary || "",
                startDate: startDateTime,
                endDate: endDateTime,
                allDay: isAllDay,
                familyId,
                email,
            };

            googleEvents.push(googleEvent);
        });

        // Prepare for the next page if it exists
        pageToken = data.nextPageToken;
    } while (pageToken);

    return { googleEvents, success: true };
}