import type { JsapiPayParams } from '../types';

type WeixinJsBridge = {
  invoke(
    api: 'getBrandWCPayRequest',
    params: JsapiPayParams,
    callback: (result: { err_msg?: string }) => void,
  ): void;
};

declare global {
  interface Window {
    WeixinJSBridge?: WeixinJsBridge;
  }
}

export function isWeChatBrowser() {
  return /MicroMessenger/i.test(navigator.userAgent);
}

export function invokeWechatJsapiPay(params: JsapiPayParams): Promise<'ok' | 'cancel'> {
  return new Promise((resolve, reject) => {
    const invoke = () => {
      const bridge = window.WeixinJSBridge;
      if (!bridge) {
        reject(new Error('当前环境不支持微信支付，请在微信内打开'));
        return;
      }
      bridge.invoke('getBrandWCPayRequest', params, (result) => {
        const message = result.err_msg ?? '';
        if (message === 'get_brand_wcpay_request:ok') {
          resolve('ok');
          return;
        }
        if (message === 'get_brand_wcpay_request:cancel') {
          resolve('cancel');
          return;
        }
        reject(new Error(message || '微信支付失败'));
      });
    };

    if (typeof window.WeixinJSBridge === 'undefined') {
      document.addEventListener('WeixinJSBridgeReady', invoke, { once: true });
      return;
    }
    invoke();
  });
}
