import Taro from '@tarojs/taro'

export interface InviteParams {
  inviter?: string
  source?: string
  t?: string
}

const STORAGE_KEY = 'invite_params'

export function parseInviteParams(options: any): InviteParams | null {
  try {
    const query = options?.query || options || {}
    if (query.inviter) {
      return {
        inviter: String(query.inviter),
        source: query.source ? String(query.source) : 'share',
        t: query.t ? String(query.t) : undefined,
      }
    }
    if (query.scene && String(query.scene).startsWith('uid_')) {
      return {
        inviter: String(query.scene).replace('uid_', ''),
        source: 'qrcode',
        t: Date.now().toString(),
      }
    }
    return null
  } catch (_error) {
    return null
  }
}

export function saveInviteParams(params: InviteParams) {
  Taro.setStorageSync(STORAGE_KEY, {
    ...params,
    timestamp: Date.now(),
  })
}

export function getStoredInviteParams(): InviteParams | null {
  const stored = Taro.getStorageSync(STORAGE_KEY)
  if (!stored?.inviter) return null
  return {
    inviter: stored.inviter,
    source: stored.source,
    t: stored.t,
  }
}

export function clearInviteParams() {
  Taro.removeStorageSync(STORAGE_KEY)
}

export function hasPendingInvite() {
  return !!getStoredInviteParams()?.inviter
}

export function trackInviteSource(_source: string, _inviterId?: number) {
  return
}

export async function checkAndHandleInviteRelation() {
  clearInviteParams()
  return true
}
