import apiClient from './api';

export const cartService = {
  /**
   * Get user's cart
   * @param {string} userId - User ID
   * @returns {Promise} Promise with the API response
   */
  getCart: async (userId) => {
    try {
      const response = await apiClient.get(`/cart/${userId}`);
      return response.data;
    } catch (error) {
      throw error.response?.data || { message: 'An unknown error occurred' };
    }
  },

  /**
   * Add item to cart
   * @param {Object} cartItemData - Cart item data
   * @param {string} cartItemData.userId - User ID
   * @param {string} cartItemData.productId - Product ID
   * @param {number} [cartItemData.quantity=1] - Quantity to add
   * @returns {Promise} Promise with the API response
   */
  addToCart: async (cartItemData) => {
    try {
      const response = await apiClient.post('/cart/add', cartItemData);
      return response.data;
    } catch (error) {
      throw error.response?.data || { message: 'An unknown error occurred' };
    }
  },

  /**
   * Update cart item quantity
   * @param {Object} updateData - Update data
   * @param {string} updateData.userId - User ID
   * @param {string} updateData.productId - Product ID
   * @param {number} updateData.quantity - New quantity (0 to remove)
   * @returns {Promise} Promise with the API response
   */
  updateCartItem: async (updateData) => {
    try {
      const response = await apiClient.put('/cart/update', updateData);
      return response.data;
    } catch (error) {
      throw error.response?.data || { message: 'An unknown error occurred' };
    }
  },

  /**
   * Clear all items from cart
   * @param {string} userId - User ID
   * @returns {Promise} Promise with the API response
   */
  clearCart: async (userId) => {
    try {
      const response = await apiClient.delete(`/cart/clear/${userId}`);
      return response.data;
    } catch (error) {
      throw error.response?.data || { message: 'An unknown error occurred' };
    }
  },

  /**
   * Checkout cart and create order
   * @param {Object} checkoutData - Checkout data
   * @param {string} checkoutData.userId - User ID
   * @param {string} checkoutData.shippingAddress - Shipping address
   * @returns {Promise} Promise with the API response
   */
  checkout: async (checkoutData) => {
    try {
      const response = await apiClient.post('/cart/checkout', checkoutData);
      return response.data;
    } catch (error) {
      throw error.response?.data || { message: 'An unknown error occurred' };
    }
  }
};

export default cartService;