// Functions for syncing conversations and projects with the server

// API URL - update this to your actual server URL
const API_BASE_URL = 'https://sharegift.shop/ShareGiftBot/extention/token_api.php';

// Function to save a conversation to the server
async function saveConversationToServer(token, conversationId) {
    try {
        // Create form data for the POST request
        const formData = new FormData();
        formData.append('token', token);
        formData.append('conversation_id', conversationId);
        
        // Make the API request to save the conversation
        const response = await fetch(`${API_BASE_URL}?action=save_conversation`, {
            method: 'POST',
            body: formData,
            mode: 'cors',
            credentials: 'omit'
        });
        
        if (!response.ok) {
            throw new Error('API request failed with status: ' + response.status);
        }
        
        const responseData = await response.json();
        
        if (!responseData.success) {
            console.error('Error saving conversation to server:', responseData.message);
            return false;
        }
        
        console.log('Conversation saved to server successfully');
        return true;
    } catch (error) {
        console.error('Error saving conversation to server:', error);
        return false;
    }
}

// Function to save a project to the server
async function saveProjectToServer(token, projectId) {
    try {
        // Create form data for the POST request
        const formData = new FormData();
        formData.append('token', token);
        formData.append('project_id', projectId);
        
        // Make the API request to save the project
        const response = await fetch(`${API_BASE_URL}?action=save_project`, {
            method: 'POST',
            body: formData,
            mode: 'cors',
            credentials: 'omit'
        });
        
        if (!response.ok) {
            throw new Error('API request failed with status: ' + response.status);
        }
        
        const responseData = await response.json();
        
        if (!responseData.success) {
            console.error('Error saving project to server:', responseData.message);
            return false;
        }
        
        console.log('Project saved to server successfully');
        return true;
    } catch (error) {
        console.error('Error saving project to server:', error);
        return false;
    }
}

// Function to get conversations from the server
async function getConversationsFromServer(token) {
    try {
        // Create form data for the POST request
        const formData = new FormData();
        formData.append('token', token);
        
        // Make the API request to get conversations
        const response = await fetch(`${API_BASE_URL}?action=get_conversations`, {
            method: 'POST',
            body: formData,
            mode: 'cors',
            credentials: 'omit'
        });
        
        if (!response.ok) {
            throw new Error('API request failed with status: ' + response.status);
        }
        
        const responseData = await response.json();
        
        if (!responseData.success) {
            console.error('Error getting conversations from server:', responseData.message);
            return [];
        }
        
        console.log('Conversations retrieved from server successfully');
        return responseData.data || [];
    } catch (error) {
        console.error('Error getting conversations from server:', error);
        return [];
    }
}

// Function to get projects from the server
async function getProjectsFromServer(token) {
    try {
        // Create form data for the POST request
        const formData = new FormData();
        formData.append('token', token);
        
        // Make the API request to get projects
        const response = await fetch(`${API_BASE_URL}?action=get_projects`, {
            method: 'POST',
            body: formData,
            mode: 'cors',
            credentials: 'omit'
        });
        
        if (!response.ok) {
            throw new Error('API request failed with status: ' + response.status);
        }
        
        const responseData = await response.json();
        
        if (!responseData.success) {
            console.error('Error getting projects from server:', responseData.message);
            return [];
        }
        
        console.log('Projects retrieved from server successfully');
        return responseData.data || [];
    } catch (error) {
        console.error('Error getting projects from server:', error);
        return [];
    }
}

// Function to sync conversations with the server
async function syncConversationsWithServer(token) {
    try {
        // Get conversations from server
        const serverConversations = await getConversationsFromServer(token);
        
        // Get local conversations
        const result = await new Promise(resolve => {
            chrome.storage.local.get({ conversations: [] }, resolve);
        });
        
        let localConversations = result.conversations || [];
        
        // Merge server and local conversations
        const allConversations = [...new Set([...localConversations, ...serverConversations])];
        
        // Save merged conversations to local storage
        await new Promise(resolve => {
            chrome.storage.local.set({ conversations: allConversations }, resolve);
        });
        
        console.log('Conversations synced with server successfully');
        return true;
    } catch (error) {
        console.error('Error syncing conversations with server:', error);
        return false;
    }
}
// Function to sync projects with the server
async function syncProjectsWithServer(token) {
    try {
        // Get projects from server
        const serverProjects = await getProjectsFromServer(token);
        
        // Get local projects
        const result = await new Promise(resolve => {
            chrome.storage.local.get({ projects: [] }, resolve);
        });
        
        let localProjects = result.projects || [];
        
        // Merge server and local projects
        const allProjects = [...new Set([...localProjects, ...serverProjects])];
        
        // Save merged projects to local storage
        await new Promise(resolve => {
            chrome.storage.local.set({ projects: allProjects }, resolve);
        });
        
        console.log('Projects synced with server successfully');
        return true;
    } catch (error) {
        console.error('Error syncing projects with server:', error);
        return false;
    }
}

// Export functions for use in background.js
const serverSync = {
    saveConversationToServer,
    saveProjectToServer,
    getConversationsFromServer,
    getProjectsFromServer,
    syncConversationsWithServer,
    syncProjectsWithServer
};

// Only export as a module - window is not available in service workers
export default serverSync;
