import axios from 'axios';

declare global {
  interface Window {
    __API_BASE_URL__?: string;
  }
}

const apiBaseUrl = window.__API_BASE_URL__ || 'http://localhost:5173/api';

const apiClient = axios.create({
  baseURL: apiBaseUrl,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

const showNotification = (message: string, type: 'error' | 'success' = 'error') => {
  if ((window as any).showToast) {
    (window as any).showToast(message, type);
  } else {
    window.alert(message);
  }
};

apiClient.interceptors.response.use(
  (response) => {
    const data = response.data;
    console.log('API Response:', response.config.url, data);
    
    // Handle business errors even if status is 200
    if (data && typeof data === 'object' && (data.success === false || data.Success === false)) {
      const errors = data.errors || data.Errors;
      const message = data.message || data.Message;
      
      const errorMessage = errors && Array.isArray(errors) && errors.length > 0 
        ? errors.join('\n') 
        : message || '操作失败';
      
      console.error('Business Error:', errorMessage);
      showNotification(errorMessage, 'error');
      return Promise.reject(new Error(errorMessage));
    }
    return response;
  },
  (error) => {
    console.error('API Error:', error);
    let errorMessage = '网络错误，请稍后再试';
    
    if (error.response && error.response.data) {
      const data = error.response.data;
      const errors = data.errors || data.Errors;
      const message = data.message || data.Message;

      if (errors && Array.isArray(errors) && errors.length > 0) {
        errorMessage = errors.join('\n');
      } else if (message) {
        errorMessage = message;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    showNotification(errorMessage, 'error');
    return Promise.reject(error);
  }
);

export default apiClient;
