import { defineStore } from 'pinia'
import { ref } from 'vue'
import { post } from '../utils/request'

export const useUserStore = defineStore('user', () => {
  const token = ref(uni.getStorageSync('admin_token') || '')
  const adminInfo = ref(null)

  function setToken(val) {
    token.value = val
    uni.setStorageSync('admin_token', val)
    uni.setStorageSync('admin_token_expiry', Date.now() + 7 * 24 * 3600 * 1000)
  }

  function clearToken() {
    token.value = ''
    adminInfo.value = null
    uni.removeStorageSync('admin_token')
    uni.removeStorageSync('admin_token_expiry')
  }

  async function login(credentials) {
    const data = await post('/api/v1/admin/login', credentials)
    setToken(data.token)
    adminInfo.value = {
      admin_id: data.admin_id,
      username: data.username,
      real_name: data.real_name,
      role: data.role
    }
    return data
  }

  function isLoggedIn() {
    if (!token.value) return false
    const expiry = uni.getStorageSync('admin_token_expiry') || 0
    if (Date.now() > expiry) {
      clearToken()
      return false
    }
    return true
  }

  return { token, adminInfo, setToken, clearToken, login, isLoggedIn }
})
