/**
 * Offscreen Document for SQLite Worker
 * 
 * This document hosts the Dedicated Worker that runs SQLite WASM
 * with OPFS sync access.
 */

const worker = new Worker(new URL('./dist/workers/sqlite-worker.js', import.meta.url), {
    type: 'module'
});

// Relay messages between background and worker
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'sqlite_request') {
        // Forward to worker
        worker.postMessage({
            sqliteRequestId: message.sqliteRequestId,
            operation: message.operation,
            params: message.params
        });
        
        // Response will come via worker.onmessage
        return true; // Keep channel open for async response
    }
});

// Handle worker responses
worker.onmessage = (e) => {
    const { sqliteRequestId, result, error } = e.data;
    
    // Send response back to background
    chrome.runtime.sendMessage({
        type: 'sqlite_response',
        sqliteRequestId,
        result,
        error
    });
};

self.addEventListener('beforeunload', () => {
    worker.terminate();
});