import axios from 'axios';
import toast from 'react-hot-toast';
import ENV_CONFIG from '../config/env.js';

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

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

// 仅开发环境打印；生产构建绝不输出，避免泄露基础设施地址
if (process.env.NODE_ENV === 'development') {
  console.log('🌐 Go Backend URL:', ENV_CONFIG.API_URL);
  console.log('🔐 Auth Center URL:', ENV_CONFIG.AUTH_API_URL);
}

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

api.interceptors.request.use(addToken, (e) => Promise.reject(e));
authCenterAPI.interceptors.request.use(addToken, (e) => Promise.reject(e));

api.interceptors.response.use(
  (res) => res,
  (error) => {
    const message = error.response?.data?.message || error.response?.data?.error || '网络错误，请稍后重试';
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    toast.error(message);
    return Promise.reject(error);
  }
);

authCenterAPI.interceptors.response.use(
  (res) => res,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export const authAPI = {
  me: () => authCenterAPI.get('/api/auth/me'),
  verify: (token) => authCenterAPI.post('/api/auth/verify', { token }),
  updateProfile: (data) => authCenterAPI.put('/api/auth/profile', data),
};

export default api;
