import Taro from '@tarojs/taro'

export type LngLat = { lng: string; lat: string }

const isLocationDenied = (e: any) => {
  const msg = String(e?.errMsg || e?.message || e || '')
  return (
    msg.includes('auth deny') ||
    msg.includes('authorize') ||
    msg.includes('permission') ||
    msg.includes('denied') ||
    msg.includes('scope.userLocation')
  )
}

/**
 * Best-effort: tries to fetch current GPS location (gcj02).
 * - Returns null on failure.
 * - If denied, it prompts user to open settings.
 */
export async function getCurrentLngLat(purpose = '保存地址需要获取您的定位信息，请在设置中开启定位权限后重试。'): Promise<LngLat | null> {
  try {
    const r = await Taro.getLocation({ type: 'gcj02' })
    return { lng: String(r.longitude), lat: String(r.latitude) }
  } catch (e: any) {
    console.warn('获取定位失败:', e)
    if (isLocationDenied(e)) {
      try {
        const modal = await Taro.showModal({
          title: '需要定位权限',
          content: purpose,
          confirmText: '去设置'
        })
        if (modal.confirm) {
          await Taro.openSetting()
          // User may have toggled permission; try once again.
          const r = await Taro.getLocation({ type: 'gcj02' })
          return { lng: String(r.longitude), lat: String(r.latitude) }
        }
      } catch (_e) {
        // ignore
      }
      return null
    }

    try {
      await Taro.showToast({ title: '获取定位失败', icon: 'none' })
    } catch (_e) {
      // ignore
    }
    return null
  }
}
