/**
 * API Service for handling server communication
 */
const ApiService = {
    /**
     * Gets the current connection from localStorage
     * @returns {Object|null} The connection object or null if not found
     */
    getCurrentConnection() {
        const connection = localStorage.getItem("lastConnection");
        return connection ? JSON.parse(connection) : null;
    },

    /**
     * Sets the current connection in localStorage
     * @param {Object} connection - The connection object to store
     */
    setCurrentConnection(connection) {
        localStorage.setItem("lastConnection", JSON.stringify(connection));
    },

    /**
     * Fetches nodes from the server
     * @param {string|null} parentId - The ID of the parent node
     * @returns {Promise} Promise resolving to the node data
     */
    async fetchNodes(parentId) {
        const connection = this.getCurrentConnection();
        if (!connection) {
            throw new Error('Please connect first!');
        }

        try {
            const response = await fetch(`/api/nodes${parentId ? `?parentId=${parentId}` : ''}`, {
                headers: {
                    'Content-Type': 'application/json',
                    'Connection-Id': connection.id
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('Error fetching nodes:', error);
            throw error;
        }
    },

    /**
     * Fetches content types for a node
     * @param {string} nodeId - The ID of the node
     * @returns {Promise} Promise resolving to the content types
     */
    async fetchContentTypes(nodeId) {
        const connection = this.getCurrentConnection();
        if (!connection) {
            throw new Error('Please connect first!');
        }

        try {
            const response = await fetch(`/api/content-types?nodeId=${nodeId}`, {
                headers: {
                    'Content-Type': 'application/json',
                    'Connection-Id': connection.id
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('Error fetching content types:', error);
            throw error;
        }
    }
}; 