let defined = false;

export const HOOK_TEST_NET_STORAGE_KEY = '__NET_ENV_DEBUG';

export function hookTestNet(force = false) {
  if (defined && !force) {
    return;
  }

  defined = true;

  if (typeof window === 'undefined') {
    return;
  }

  // @ts-ignore
  const rawResult = window.isTestNet;

  Object.defineProperty(window, 'isTestNet', {
    get() {
      const storage = wx.getStorageSync(HOOK_TEST_NET_STORAGE_KEY);
      const result = storage === 'test';
      return result;
    },
    set(value) {
      wx.setStorageSync(HOOK_TEST_NET_STORAGE_KEY, value ? 'test' : 'release');
    },
  });

  if (typeof rawResult === 'boolean') {
    // @ts-ignore
    window.isTestNet = rawResult;
  }
}
