(async function () {
    console.log('Update API script loaded!');

    // Function to save data to the database
    async function saveDataToDatabase(type, data) {
        try {
            const response = await fetch('/wp-json/renesse/v1/save-data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ type, data }),
            });

            if (!response.ok) {
                const result = await response.json();
                console.error(`Error saving ${type} data:`, result);
            }
        } catch (error) {
            console.error(`Request to save ${type} data failed:`, error);
        }
    }

    // Function to fetch data from an API endpoint
    async function fetchDataFromApi(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Failed to fetch data from ${url} - Status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error(`Error fetching data from ${url}:`, error);
            return [];
        }
    }

    // Function to check last update and process data if needed
    async function processType(type, apiUrl) {
        try {
            const lastUpdate = await fetch(`/wp-json/renesse/v1/check-data-timestamp?type=${type}`);
            const lastUpdateData = await lastUpdate.json();

            if (!lastUpdateData || !lastUpdateData.last_updated) {
                console.warn(`No last_updated field found for ${type}. Assuming first-time setup.`);
                const data = await fetchDataFromApi(apiUrl);
                if (data.length > 0) {
                    await saveDataToDatabase(type, data);
                }
                return;
            }

            const lastUpdatedDate = new Date(lastUpdateData.last_updated);
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            if (lastUpdatedDate < today) {
                const data = await fetchDataFromApi(apiUrl);
                if (data.length > 0) {
                    await saveDataToDatabase(type, data);
                }
            }
        } catch (error) {
            console.error(`Error processing ${type}:`, error);
        }
    }

    // API endpoints
    const endpoints = {
        events: 'https://www.renesseaanzee.nl/wp-json/app/v2/events?key=83b6ea44-9765-46b9-b391-8fd55ba49015&inside=1',
        activities: 'https://www.renesseaanzee.nl/wp-json/app/v1/activities?key=83b6ea44-9765-46b9-b391-8fd55ba49015&inside=1',
    };

    // Process both types
    await Promise.all([
        processType('events', endpoints.events),
        processType('activities', endpoints.activities),
    ]);

})();