import axios from 'axios';

const request = axios.create({
  baseURL: '',
  timeout: 15000,
});

request.interceptors.request.use((config) => {
  const token = localStorage.getItem('seller_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

request.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.code === 401) {
      localStorage.removeItem('seller_token');
      localStorage.removeItem('seller_info');
      window.location.href = '/login';
      return Promise.reject(new Error(data.message || '登录已过期'));
    }
    if (data.code >= 200 && data.code < 300) {
      return data;
    }
    return Promise.reject(new Error(data.message || '请求失败'));
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('seller_token');
      localStorage.removeItem('seller_info');
      window.location.href = '/login';
      return Promise.reject(new Error('登录已过期'));
    }
    const message = error.response?.data?.message || error.message || '网络请求失败';
    return Promise.reject(new Error(message));
  },
);

export default request;
