import { http } from '../utils/request'
import { storage } from '../utils/storage'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(storage.get('token') || '')
  const profile = ref<any>(null)

  const isLoggedIn = computed(() => !!token.value)

  async function login(account: string, password: string) {
    const res: any = await http.post('/auth/login', { account, password })
    token.value = res.accessToken
    http.setToken(res.accessToken)
    storage.set('token', res.accessToken)
    await fetchProfile()
    return res
  }

  async function register(data: { phone?: string; email?: string; password: string; nickname?: string }) {
    const res: any = await http.post('/auth/register', data)
    token.value = res.accessToken
    http.setToken(res.accessToken)
    storage.set('token', res.accessToken)
    await fetchProfile()
    return res
  }

  async function fetchProfile() {
    profile.value = await http.get('/auth/profile')
  }

  function logout() {
    token.value = ''
    profile.value = null
    http.setToken('')
    storage.remove('token')
    uni.redirectTo({ url: '/pages/login/index' })
  }

  function initToken() {
    const saved = storage.get('token')
    if (saved) {
      token.value = saved
      http.setToken(saved)
    }
  }

  return { token, profile, isLoggedIn, login, register, fetchProfile, logout, initToken }
})
