import axios from 'axios';
import { authUtils } from './auth';

const API_BASE_URL = 'https://domaintestaccount.store/api/v1';

// Create axios instance
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add request interceptor to add auth token
api.interceptors.request.use(
  (config) => {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
      const token = authUtils.decrypt(encryptedToken);
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Add response interceptor to handle errors
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    
    // 处理401错误和token刷新
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      try {
        // 尝试刷新token
        const refreshToken = authUtils.decrypt(localStorage.getItem('refreshToken'));
        if (refreshToken) {
          const response = await api.post('/auth/refresh', { refresh_token: refreshToken });
          const { access_token, refresh_token } = response.data;
          
          // 更新存储的token
          localStorage.setItem('token', authUtils.encrypt(access_token));
          localStorage.setItem('refreshToken', authUtils.encrypt(refreshToken));
          
          // 更新当前请求的token
          originalRequest.headers.Authorization = `Bearer ${access_token}`;
          
          // 广播token更新
          authUtils.broadcastAuthChange('token_refreshed', { access_token });
          
          // 重试原始请求
          return api(originalRequest);
        }
      } catch (refreshError) {
        // 刷新token失败，清除认证信息
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('user');
        
        // 广播登出事件
        authUtils.broadcastAuthChange('logout');
        
        // 可以在这里添加重定向到登录页面的逻辑
        window.location.href = '/login';
      }
    }
    
    return Promise.reject(error);
  }
);

// Auth APIs
export const auth = {
  register: (userData) => api.post('/auth/register', userData),
  login: (credentials) => api.post('/auth/login', credentials),
  getCurrentUser: () => api.get('/auth/me'),
};

// Users APIs
export const users = {
  updateProfile: (userData) => api.put('/auth/profile', userData),
  uploadAvatar: (formData) => api.post('/auth/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }),
};

// Posts APIs
export const posts = {
  list: (params) => api.get('/posts', { params }),
  getById: (id) => api.get(`/posts/${id}`),
  create: (postData) => api.post('/posts', postData),
  update: (id, postData) => api.put(`/posts/${id}`, postData),
  delete: (id) => api.delete(`/posts/${id}`),
  like: (id) => api.post(`/posts/${id}/like`),
  unlike: (id) => api.delete(`/posts/${id}/like`),
  getUserPosts: (params) => api.get('/posts/my/posts', { params }),
};

// Comments APIs
export const comments = {
  list: (postId) => api.get(`/comments?post_id=${postId}`),
  create: (postId, commentData) => api.post('/comments', { ...commentData, post_id: postId }),
  update: (postId, commentId, commentData) => 
    api.put(`/comments/${commentId}`, commentData),
  delete: (postId, commentId) => api.delete(`/comments/${commentId}`),
};

// Upload APIs
export const uploads = {
  uploadImage: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/uploads/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  uploadImages: (files) => {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    return api.post('/uploads/images', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export default {
  auth,
  users,
  posts,
  comments,
  uploads
}
