import Taro from '@tarojs/taro'

/**
 * 在调用隐私相关 API / 组件前，确保用户已完成微信隐私协议授权。
 * 基础库 3.16.1+ 强制要求，未授权会抛 errno:112 / buttonId is wrong 等错误。
 * 旧基础库或不支持隐私协议的版本直接放行。
 */
export const ensurePrivacyAuthorized = (): Promise<void> => {
  return new Promise((resolve) => {
    const wxAny: any = Taro
    if (typeof wxAny.requirePrivacyAuthorize !== 'function') {
      resolve()
      return
    }
    if (typeof wxAny.getPrivacySetting === 'function') {
      wxAny.getPrivacySetting({
        success: (res: any) => {
          if (res && res.needAuthorization) {
            wxAny.requirePrivacyAuthorize({
              success: () => resolve(),
              fail: () => resolve(),
            })
          } else {
            resolve()
          }
        },
        fail: () => resolve(),
      })
    } else {
      wxAny.requirePrivacyAuthorize({
        success: () => resolve(),
        fail: () => resolve(),
      })
    }
  })
}

/**
 * 打开官方隐私协议页面（半屏协议）。
 * 返回是否成功打开。
 */
export const openPrivacyContract = (): Promise<boolean> => {
  return new Promise((resolve) => {
    const wxAny: any = Taro
    if (typeof wxAny.openPrivacyContract !== 'function') {
      resolve(false)
      return
    }
    wxAny.openPrivacyContract({
      success: () => resolve(true),
      fail: () => resolve(false),
    })
  })
}

/**
 * 检查当前用户是否需要同意隐私协议。
 */
export const checkPrivacyAuthorization = (): Promise<{
  needAuthorization: boolean
  isAuthorization: boolean
}> => {
  return new Promise((resolve) => {
    const wxAny: any = Taro
    if (typeof wxAny.getPrivacySetting !== 'function') {
      resolve({ needAuthorization: false, isAuthorization: true })
      return
    }
    wxAny.getPrivacySetting({
      success: (res: any) => {
        resolve({
          needAuthorization: !!res?.needAuthorization,
          isAuthorization: !!res?.isAuthorization,
        })
      },
      fail: () => resolve({ needAuthorization: false, isAuthorization: true }),
    })
  })
}
