document.addEventListener("DOMContentLoaded", async function () {
    async function performUploads() {
        try {
            const uploadFile = await window.electronAPI.readFile('usersDestTemp.json');
            const uploadData = JSON.parse(uploadFile.content);

            const uploadPromises = uploadData.users.map(async (user) => {
                try {
                    const response = await fetch(uploadData.filePath);
                    if (!response.ok) {
                        throw new Error('Failed to fetch file');
                    }
                    const file = await response.blob();
                    if (!file.size) {
                        throw new Error('File is empty or could not be loaded');
                    }

                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('idUser', user.userId);
                    formData.append('nameOfFile', user.fileName);
                    formData.append('sizeOfFile', file.size);

                    // Debugging FormData content
                    for (let [key, value] of formData.entries()) {
                        console.log(key, value instanceof Blob ? `Blob (${value.size} bytes)` : value);
                    }

                    const url = `http://${user.destIp}:${user.destPort}/upload`;
                    const uploadResponse = await fetch(url, {
                        method: 'POST',
                        body: formData
                    });

                    if (!uploadResponse.ok) {
                        try {
                            const errorResponse = await uploadResponse.json();
                            throw new Error(`HTTP error during file upload to ${user.userId}: ${errorResponse.message}`);
                        } catch (parseError) {
                            const responseText = await uploadResponse.text();
                            throw new Error(`HTTP error during file upload to ${user.userId}: ${responseText}`);
                        }
                    }

                    return {userId: user.userId, success: true, message: `Upload successful for user ${user.userId}`};
                } catch (error) {
                    console.error(`Failed to upload for user ${user.userId}:`, error);
                    return {userId: user.userId, success: false, message: `Upload failed for user ${user.userId}`};
                }
            });

            const results = await Promise.all(uploadPromises);
            results.forEach(result => {
                console.log(result.message);
            });
            console.log('All files processed. Check the console for detailed results.');
        } catch (error) {
            console.error('An error occurred during uploads:', error);
        } finally {
            await window.electronAPI.deleteFile('usersDestTemp.json');
        }
    }

    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    await performUploads();
    await timeout(10000); // Consider the necessity of this delay in production
    fadeOut('main_menu.html');
});
