import { defineStore } from 'pinia'
import { login } from '@/api/auth'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const role = ref(localStorage.getItem('role') || '') // 持久化角色
    const username = ref(localStorage.getItem('username') || '')

    const handleLogin = async (loginForm: any) => {
        try {
            const res = await login(loginForm)
            // res.data 结构: { access_token, user: { role, username, ... } }
            const data = res.data

            token.value = data.access_token
            role.value = data.user.role
            username.value = data.user.username

            // 持久化存储 (简单处理，生产环境建议加密或仅存Token)
            localStorage.setItem('token', data.access_token)
            localStorage.setItem('role', data.user.role)
            localStorage.setItem('username', data.user.username)

            return true
        } catch (error) {
            console.error(error)
            return false
        }
    }

    const logout = () => {
        token.value = ''
        role.value = ''
        username.value = ''
        localStorage.clear()
        window.location.reload()
    }

    // 辅助函数：判断当前用户是否拥有某些角色
    const hasRole = (roles: string[]) => {
        return roles.includes(role.value)
    }

    return { token, role, username, handleLogin, logout, hasRole }
})