import axios, { type AxiosInstance, type AxiosError } from 'axios';

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api/v1';

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error),
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    if (response.data && response.data.code === 200) {
      return response.data.data;
    }
    return response.data;
  },
  (error: AxiosError) => {
    if (error.response) {
      const { status } = error.response as any;
      
      switch (status) {
        case 401:
          localStorage.removeItem('token');
          localStorage.removeItem('refreshToken');
          window.location.href = '/login';
          break;
        case 403:
          console.error('没有权限访问该资源');
          break;
        case 404:
          console.error('请求的资源不存在');
          break;
        case 500:
          console.error('服务器内部错误');
          break;
        default:
          console.error('请求失败');
      }
    } else if (error.request) {
      console.error('网络请求失败，请检查网络连接');
    }
    
    return Promise.reject(error);
  },
);

// 认证API
export const authApi = {
  register: (data: { username: string; email: string; password: string; phone?: string }) =>
    api.post('/auth/register', data),
  login: (data: { username: string; password: string }) =>
    api.post('/auth/login', data),
  logout: () => api.post('/auth/logout'),
  getProfile: () => api.get('/auth/profile'),
};

// 行情API
export const marketApi = {
  getProducts: (params?: { category?: string; page?: number; size?: number }) =>
    api.get('/market/products', { params }),
  getProduct: (symbol: string) => api.get(`/market/products/${symbol}`),
  getKline: (symbol: string, params: { period: string; count?: number }) =>
    api.get(`/market/products/${symbol}/kline`, { params }),
  getTick: (symbol: string) => api.get(`/market/products/${symbol}/tick`),
  getOverview: () => api.get('/market/overview'),
};

// 技术指标API
export const indicatorsApi = {
  getIndicators: (symbol: string, params: { period: string }) =>
    api.get(`/indicators/${symbol}`, { params }),
  getMACD: (symbol: string) => api.get(`/indicators/${symbol}/macd`),
  getRSI: (symbol: string) => api.get(`/indicators/${symbol}/rsi`),
  getBollinger: (symbol: string) => api.get(`/indicators/${symbol}/bollinger`),
  getKDJ: (symbol: string) => api.get(`/indicators/${symbol}/kdj`),
};

// 期权API
export const optionsApi = {
  calculatePricing: (data: any) => api.post('/options/pricing', data),
  getOptionChain: (underlying: string) => api.get(`/options/chain/${underlying}`),
  getVolatilitySurface: (underlying: string) => api.get(`/options/volatility-surface/${underlying}`),
  getStrategies: () => api.get('/options/strategies'),
};

// AI分析API
export const aiApi = {
  analyzeSymbol: (symbol: string) => api.get(`/ai/analyze/${symbol}`),
};

// 热点事件API
export const eventsApi = {
  getEvents: (params?: any) => api.get('/events', { params }),
  getEventById: (id: string) => api.get(`/events/${id}`),
};

// 自选股API
export const watchlistApi = {
  getWatchlist: () => api.get('/watchlist'),
  addToWatchlist: (data: { symbol: string; alertPrice?: number }) =>
    api.post('/watchlist', data),
  removeFromWatchlist: (symbol: string) => api.delete(`/watchlist/${symbol}`),
};

export default api;
