import { ref } from 'vue'

const LOGIN_TIME_STORAGE_KEY = 'loginTime'

function storedActivityTime() {
  return Number.parseInt(localStorage.getItem(LOGIN_TIME_STORAGE_KEY) || '0', 10) || 0
}

/**
 * 会话按“最后活跃时间”计算，而不是从首次登录起固定倒计时。
 * 该 ref 被认证 store 与请求层共享，确保 API 活动可以立即影响路由守卫。
 */
export const sessionActivityTime = ref(storedActivityTime())

export function startSessionActivity() {
  sessionActivityTime.value = Date.now()
  localStorage.setItem(LOGIN_TIME_STORAGE_KEY, String(sessionActivityTime.value))
}

export function touchSessionActivity() {
  if (!sessionActivityTime.value) return
  startSessionActivity()
}

export function syncSessionActivity() {
  sessionActivityTime.value = storedActivityTime()
}

export function clearSessionActivity() {
  sessionActivityTime.value = 0
  localStorage.removeItem(LOGIN_TIME_STORAGE_KEY)
}
