import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '@/api/request'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const expiresAt = ref(localStorage.getItem('expiresAt') || '')

  const isAuthenticated = computed(() => {
    if (!token.value || !expiresAt.value) return false
    // 检查token是否过期
    return new Date(expiresAt.value) > new Date()
  })

  const login = async (password) => {
    try {
      const response = await request.post('/Auth/Login', { password })
      const { token: newToken, expiresAt: newExpiresAt } = response.data
      
      token.value = newToken
      expiresAt.value = newExpiresAt
      
      localStorage.setItem('token', newToken)
      localStorage.setItem('expiresAt', newExpiresAt)
      
      return true
    } catch (error) {
      if (error.response?.status === 401) {
        throw new Error('密码错误')
      }
      throw new Error('登录失败，请稍后重试')
    }
  }

  const logout = () => {
    token.value = ''
    expiresAt.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('expiresAt')
  }

  return {
    token,
    expiresAt,
    isAuthenticated,
    login,
    logout,
  }
})
