import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || 'http://localhost:8080',
  timeout: 15000,
});

request.interceptors.request.use((config) => {
  const token = localStorage.getItem('admin_token');
  if (token) {
    config.headers['X-Admin-Token'] = token;
  }
  return config;
});

request.interceptors.response.use(
  (resp) => resp.data,
  (error) => {
    const status = error.response?.status;
    if (status === 401) {
      localStorage.removeItem('admin_token');
      ElMessage.error('登录已失效，请重新登录');
      router.replace({ name: 'Login' });
    } else {
      ElMessage.error(error.response?.data?.message || error.message || '请求失败');
    }
    return Promise.reject(error);
  },
);

export default request;
