/**
 * 用户状态管理 (Pinia)
 * Token 持久化 + /auth/me 获取完整用户上下文(含 data_scope, menu_keys)
 */

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

// 用户信息类型（对应后端 CurrentUserPayload）
interface UserInfo {
    user_id: string
    username: string
    real_name: string | null
    dept_id: string | null
    dept_name: string | null
    role_id: string | null
    role_name: string | null
    data_scope: string
    menu_keys: string[]
}

export const useUserStore = defineStore('user', () => {
    // ---- State ----
    const token = ref<string>(localStorage.getItem('crm_token') || '')
    const userInfo = ref<UserInfo | null>(null)

    // ---- Getters ----
    const isLoggedIn = computed(() => !!token.value)
    const username = computed(() => userInfo.value?.username || '')
    const realName = computed(() => userInfo.value?.real_name || userInfo.value?.username || '')
    const dataScope = computed(() => userInfo.value?.data_scope || 'self')
    const menuKeys = computed(() => userInfo.value?.menu_keys || [])

    // ---- Actions ----

    /** 登录：POST /api/auth/login → 拿 Token */
    async function login(loginUsername: string, password: string) {
        const data = await request.post('/api/auth/login', {
            username: loginUsername,
            password,
        }) as any

        token.value = data.access_token
        localStorage.setItem('crm_token', data.access_token)
    }

    /** 获取用户信息：GET /api/auth/me → 完整 Payload */
    async function fetchUserInfo() {
        const data = await request.get('/api/auth/me') as unknown as UserInfo
        userInfo.value = data
    }

    /** 登出 */
    function logout() {
        token.value = ''
        userInfo.value = null
        localStorage.removeItem('crm_token')
    }

    return {
        token,
        userInfo,
        isLoggedIn,
        username,
        realName,
        dataScope,
        menuKeys,
        login,
        fetchUserInfo,
        logout,
    }
})
