import * as Calendar from 'expo-calendar';

export async function fetchiPhoneCalendarEvents(familyId, email, startDate, endDate) {
    try {
        const {granted} = await Calendar.requestCalendarPermissionsAsync();

        if (!granted) {
            throw new Error("Calendar permission not granted");
        }

        const defaultCalendarSource = await Calendar.getDefaultCalendarAsync();

        if (!defaultCalendarSource) {
            throw new Error("No calendar found");
        }

        const events = await Calendar.getEventsAsync(
            [defaultCalendarSource.id],
            startDate,
            endDate
        );

        return events.map((event) => {
            let isAllDay = event.allDay || false;
            const startDateTime = new Date(event.startDate);
            let endDateTime = new Date(event.endDate);

            if (isAllDay) {
                endDateTime = startDateTime
            }

            return {
                id: event.id,
                title: event.title,
                startDate: startDateTime,
                endDate: endDateTime,
                allDay: isAllDay,
                familyId,
                email
            };
        });
    } catch (error) {
        console.error("Error fetching iPhone Calendar events: ", error);
        throw error;
    }
}