import { getMnemonic } from "$lib/wallet.svelte";
import initBreez, {
  type BindingLiquidSdk,
  connect as breezConnect,
  defaultConfig as defaultBreezConfig,
} from "@breeztech/breez-sdk-liquid/web";

initBreez();

let breezSDK: BindingLiquidSdk;
let initialized = false;

export async function getBreezSDK() {
  if (initialized) return breezSDK;

  const mnemonic = await getMnemonic();

  breezSDK = await breezConnect({
    mnemonic,
    config: defaultBreezConfig(
      "mainnet",
      "MIIBajCCARygAwIBAgIHPgwAQY4DlTAFBgMrZXAwEDEOMAwGA1UEAxMFQnJlZXowHhcNMjUwNTA1MTY1OTM5WhcNMzUwNTAzMTY1OTM5WjAnMQwwCgYDVQQKEwNBcngxFzAVBgNVBAMTDkRhbm55IE1vcmFiaXRvMCowBQYDK2VwAyEA0IP1y98gPByiIMoph1P0G6cctLb864rNXw1LRLOpXXejfjB8MA4GA1UdDwEB/wQEAwIFoDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBTaOaPuXmtLDTJVv++VYBiQr9gHCTAfBgNVHSMEGDAWgBTeqtaSVvON53SSFvxMtiCyayiYazAcBgNVHREEFTATgRFkYW5ueUBhcngtY2NuLmNvbTAFBgMrZXADQQAwJoh9BG8rEH1sOl+BpS12oNSwzgQga8ZcIAZ8Bjmd6QT4GSST0nLj06fs49pCkiULOl9ZoRIeIMc3M1XqV5UA",
    ), // this key can be shared, it's fine
  });

  breezSDK.addEventListener({
    onEvent: (e) => {
      console.log(e);
      refreshBalances();
    },
  });

  initialized = true;
  return breezSDK;
}

export async function initBalances() {
  const sdk = await getBreezSDK();
  const info = await sdk.getInfo();
  balances.balance = info.walletInfo.balanceSat;
  balances.pendingReceive = info.walletInfo.pendingReceiveSat;
  balances.pendingSend = info.walletInfo.pendingSendSat;
}

export const balances = $state({
  balance: 0,
  pendingReceive: 0,
  pendingSend: 0,
  tick: 0,
});

export async function refreshBalances() {
  const sdk = await getBreezSDK();
  const info = await sdk.getInfo();
  balances.balance = info.walletInfo.balanceSat;
  balances.pendingReceive = info.walletInfo.pendingReceiveSat;
  balances.pendingSend = info.walletInfo.pendingSendSat;
  balances.tick++;
}
