import axios from 'axios'
import { getAccessToken } from './composables/useAuth'

// 创建 axios 实例
const api = axios.create({
    baseURL: import.meta.env.VITE_API_BASE || 'https://api.yuany3721.site',
    headers: {
        'Content-Type': 'application/json',
    },
})

// 请求拦截器 - 自动添加 Authorization Header
api.interceptors.request.use(
    (config) => {
        const token = getAccessToken()
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器 - 处理 401 错误
api.interceptors.response.use(
    (response) => response,
    async (error) => {
        if (error.response?.status === 401) {
            console.warn('[API] 401 Unauthorized, redirecting to login...')
            const { login } = await import('./composables/useAuth')
            await login()
        }
        return Promise.reject(error)
    }
)

export default api
