import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi } from '@/api/modules/system'
import { SESSION_TIMEOUT } from '@/constants'

/**
 * 认证 store
 * 沿用原项目 localStorage 的登录时间戳 + 5 分钟会话超时机制
 */
export const useAuthStore = defineStore('auth', () => {
  const username = ref<string>(localStorage.getItem('username') || '')
  const loginTime = ref<number>(parseInt(localStorage.getItem('loginTime') || '0', 10) || 0)

  const isLoggedIn = computed(() => {
    if (!loginTime.value) return false
    return Date.now() - loginTime.value < SESSION_TIMEOUT
  })

  /** 登录 */
  async function login(user: string, password: string) {
    await loginApi(user, password)
    username.value = user
    loginTime.value = Date.now()
    localStorage.setItem('username', user)
    localStorage.setItem('loginTime', String(loginTime.value))
  }

  /** 续期会话（活跃时刷新） */
  function refresh() {
    if (isLoggedIn.value) {
      loginTime.value = Date.now()
      localStorage.setItem('loginTime', String(loginTime.value))
    }
  }

  /** 退出 */
  function logout() {
    username.value = ''
    loginTime.value = 0
    localStorage.removeItem('username')
    localStorage.removeItem('loginTime')
  }

  return { username, loginTime, isLoggedIn, login, refresh, logout }
})
