import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useUserStore} from '@/stores/user'
import router from '@/router'

const request = axios.create({
    baseURL: '/api',
    timeout: 10000,
})

// 请求拦截：自动带 token
request.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.token){
            config.headers.Authorization = `Bearer ${userStore.token}`
        }
        return config
    },
    (err) => Promise.reject(err)
)

// 响应拦截：统一处理 { code, data, message } + 401 跳登录
request.interceptors.response.use(
    (res) => {
        const body = res.data
        if (typeof body?.code === 'undefined') return res.data
        if (body.code === 0) return body.data
        ElMessage.error(body.message || '请求失败')
        return Promise.reject(new Error(body.message || '请求失败'))
    },
    (err) => {
        const status = err.response?.status
        if (status === 401) {
            const userStore = useUserStore()
            userStore.logout()
            ElMessage.error('登录已过期，请重新登录')
            router.push('/login')
        }else {
            ElMessage.error(err.response?.data?.message || err.message || '网络异常')
        }
        return Promise.reject(err)
    }
)

export default request