import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
});

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

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 401:
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          window.location.href = '/';
          break;
        case 429:
          throw new Error(data.error || '请求过于频繁，请稍后再试');
        case 400:
          if (data.details) {
            const firstError = data.details[0];
            throw new Error(`${firstError.field}: ${firstError.message}`);
          }
          throw new Error(data.error || '请求参数错误');
        case 500:
          throw new Error(data.error || '服务器内部错误');
        default:
          throw new Error(data.error || '请求失败');
      }
    } else if (error.request) {
      throw new Error('网络连接失败，请检查网络');
    } else {
      throw new Error('请求配置错误');
    }
  }
);

// 认证API
export const authAPI = {
  login: (username, password) => api.post('/auth/login', { username, password }),
  register: (username, password) => api.post('/auth/register', { username, password }),
};

// 彩票API
export const ticketAPI = {
  list: (page = 1, limit = 20) => api.get('/tickets', { params: { page, limit } }),
  stats: () => api.get('/tickets/stats'),
  create: (data) => api.post('/tickets', data),
  update: (id, data) => api.put(`/tickets/${id}`, data),
  delete: (id) => api.delete(`/tickets/${id}`),
};

// 开奖API
export const lotteryAPI = {
  result: (game, issue) => api.get('/lottery/result', { params: { game, issue } }),
  refresh: () => api.post('/lottery/refresh'),
  recent: (game, limit = 10) => api.get('/lottery/recent', { params: { game, limit } }),
};

// OCR API
export const ocrAPI = {
  parse: (file) => {
    const formData = new FormData();
    formData.append('image', file);
    return api.post('/ocr/parse', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  },
  getResult: (taskId) => api.get(`/ocr/result/${taskId}`),
};

export default api;
