import { ref, computed } from 'vue'
import userTracker from '@/utils/posthog/user-tracker'
import analytics from '@/utils/posthog/index'

/**
 * 用户追踪组合式函数
 *
 * 使用方式：
 * const {
 *   isLoggedIn,
 *   onLogin,
 *   onLogout,
 *   onFavorite,
 * } = useUserTracking()
 */
export function useUserTracking() {
  // 登录状态
  const isLoggedIn = ref(false)
  // 用户ID
  const userId = ref('')

  /**
   * 用户登录
   */
  const onLogin = (params) => {
    userTracker.onLogin(params)

    if (params.success) {
      isLoggedIn.value = true
      userId.value = params.userId
    }
  }

  /**
   * 用户登出
   */
  const onLogout = () => {
    userTracker.onLogout()
    isLoggedIn.value = false
    userId.value = ''
  }

  /**
   * 微信授权
   */
  const onWechatAuth = (params) => {
    userTracker.onWechatAuth(params)
  }

  /**
   * 内容收藏
   */
  const onFavorite = (content) => {
    userTracker.onFavorite(content)
  }

  /**
   * 取消收藏
   */
  const onUnfavorite = (content) => {
    userTracker.onUnfavorite(content)
  }

  /**
   * 内容分享
   */
  const onShare = (params) => {
    userTracker.onShare(params)
  }

  /**
   * 内容点赞
   */
  const onLike = (content, isLike = true) => {
    userTracker.onLike(content, isLike)
  }

  /**
   * 获取当前用户ID
   */
  const getDistinctId = () => {
    return analytics.getDistinctId()
  }

  return {
    // 状态
    isLoggedIn,
    userId,

    // 方法
    onLogin,
    onLogout,
    onWechatAuth,
    onFavorite,
    onUnfavorite,
    onShare,
    onLike,
    getDistinctId,
  }
}

export default useUserTracking