import axios from 'axios';

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

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

// 响应拦截器 - 处理401
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/';
    }
    return Promise.reject(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' }
    });
  }
};

export default api;
