import bbnDb from './Object.js';
export default class bbnDbCenter {
    queues = {};
    async handleMessage(event) {
        const command = event.data;
        const port = event.ports?.[0];
        //bbn.fn.log("Received DB command:", command, port, "END");
        if (!port || !command?.method?.includes('.')) {
            return false;
        }
        const [scope] = command.method.split('.');
        if (scope !== 'manager' && scope !== 'object') {
            return false;
        }
        if (!command.id || !command.database) {
            this.postError(port, command?.id ?? 0, 'Invalid DB command');
            return true;
        }
        const database = command.database;
        this.queues[database] = (this.queues[database] || Promise.resolve())
            .catch(() => undefined)
            .then(async () => {
            try {
                const result = await this.execute(command);
                this.postSuccess(port, command.id, result);
            }
            catch (error) {
                this.postError(port, command.id, this.serializeError(error) + ` - DATA: ${JSON.stringify(command)}`);
            }
        });
        return true;
    }
    async execute(command) {
        const [scope, action] = command.method.split('.');
        if (!action) {
            throw new Error(`Invalid DB method: ${command.method}`);
        }
        if (scope === 'manager') {
            return this.executeManager(action, command.args || []);
        }
        if (scope === 'object') {
            return this.executeObject(action, [command.database, ...(command.args || [])]);
        }
        throw new Error(`Unknown DB command scope: ${scope}`);
    }
    async executeManager(action, args) {
        const fn = bbnDb[action];
        if (typeof fn !== 'function') {
            throw new Error(`Unknown DB manager method: ${action}`);
        }
        return fn.apply(bbnDb, args);
    }
    async executeObject(action, args) {
        const [database, ...methodArgs] = args;
        if (!database) {
            throw new Error('Missing database name for object method');
        }
        bbn.fn.log(`Executing object method: ${action} on database: ${database}`);
        const dbo = await bbnDb.open(database);
        const fn = dbo[action];
        if (typeof fn !== 'function') {
            throw new Error(`Unknown DB object method: ${action}`);
        }
        return fn.apply(dbo, methodArgs);
    }
    postSuccess(port, id, result) {
        port.postMessage({
            id,
            ok: true,
            result
        });
        port.close();
    }
    postError(port, id, error) {
        port.postMessage({
            id,
            ok: false,
            error
        });
        port.close();
    }
    serializeError(error) {
        if (error instanceof Error) {
            return error.message;
        }
        return String(error);
    }
}
