import { RpcHandler, type RpcCallback } from './generated/fedimint_client_uniffi';
export * from './index';

class RpcService {
    private static instance: RpcHandler | null = null;
    private static dbPath: string | null = null;

    static setup(path: string) {
        if (this.instance) {
            console.log("RPC Service already initialized");
            return;
        }
        console.log("Initializing RPC Service with path :", path);
        this.dbPath = path;
        try {
            this.instance = new RpcHandler(path);
        } catch (e: any) {
            console.error("RPC Service initialization failed:", e.msg || e.message || JSON.stringify(e));
            throw e;
        }
    }

    static async sendRpc(json: string): Promise<string> {
        if (!this.instance) {
            throw new Error("RPC Service not initialized. Call setup() first.");
        }
        return new Promise((resolve, reject) => {
            try {
                const callback: RpcCallback = {
                    onResponse: (response: string) => {
                        resolve(response);
                    }
                };
                this.instance!.rpc(json, callback);
            } catch (e) {
                reject(e);
            }
        });
    }
}

export function setup(path: string) {
    RpcService.setup(path);
}

export function sendRpc(json: string): Promise<string> {
    return RpcService.sendRpc(json);
}
