// IndexedDB utility functions for widget caching

const DB_NAME = 'onvo-dashboard-cache';
const DB_VERSION = 1;
const WIDGET_CACHE_STORE = 'widget-cache';

// Initialize the database
export const initDB = (): Promise<IDBDatabase> => {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open(DB_NAME, DB_VERSION);

        request.onerror = () => {
            console.error('Error opening IndexedDB');
            reject(request.error);
        };

        request.onsuccess = () => {
            resolve(request.result);
        };

        request.onupgradeneeded = (event) => {
            const db = (event.target as IDBOpenDBRequest).result;

            // Create the widget cache store if it doesn't exist
            if (!db.objectStoreNames.contains(WIDGET_CACHE_STORE)) {
                const store = db.createObjectStore(WIDGET_CACHE_STORE, { keyPath: 'id' });
                store.createIndex('timestamp', 'timestamp', { unique: false });
            }
        };
    });
};

// Get widget cache from IndexedDB
export const getWidgetCache = async (widgetId: string): Promise<any> => {
    try {
        const db = await initDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(WIDGET_CACHE_STORE, 'readonly');
            const store = transaction.objectStore(WIDGET_CACHE_STORE);
            const request = store.get(widgetId);

            request.onsuccess = () => {
                resolve(request.result?.data || null);
            };

            request.onerror = () => {
                reject(request.error);
            };
        });
    } catch (error) {
        console.error('Error getting widget cache from IndexedDB:', error);
        return null;
    }
};

// Save widget cache to IndexedDB
export const saveWidgetCache = async (widgetId: string, data: any): Promise<void> => {
    try {
        const db = await initDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(WIDGET_CACHE_STORE, 'readwrite');
            const store = transaction.objectStore(WIDGET_CACHE_STORE);

            const cacheItem = {
                id: widgetId,
                data,
                timestamp: Date.now()
            };

            const request = store.put(cacheItem);

            request.onsuccess = () => {
                resolve();
            };

            request.onerror = () => {
                reject(request.error);
            };
        });
    } catch (error) {
        console.error('Error saving widget cache to IndexedDB:', error);
    }
}; 