import axios from 'axios';

// Create axios instance with default config
const client = axios.create({
    baseURL: '/v1',
    timeout: 10000,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'application/json',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
});

// Request interceptor
client.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// Response interceptor
client.interceptors.response.use(
    response => {
        return response
    },
    error => {
        // Handle HTTP errors here
        if (error.response) {
            // Handle 401 Unauthorized error
            if (error.response.status === 401) {
                const redirectUrl = encodeURIComponent(window.location.href);
                window.location.href = `/v1/auth/wechat?redirect=${redirectUrl}`;
                return;
            }
            // Server responded with error status
            console.error('API Error:', error.response.status, error.response.data);
        } else if (error.request) {
            // Request made but no response received
            console.error('API Error: No response received', error.request);
        } else {
            // Something else happened
            console.error('API Error:', error.message);
        }
        return Promise.reject(error);
    }
);

export default client;
