import apiFetch from '@wordpress/api-fetch';

const API_BASE = '/wp/v2/dlift_discount_rule';

/**
 * Fetch all rules
 */
export const fetchRules = async () => {
  try {
    return await apiFetch({
      path: `${API_BASE}?per_page=100`,
    });
  } catch (error) {
    console.error('Error fetching rules:', error);
    throw error;
  }
};

/**
 * Create a new rule
 */
export const createRule = async (ruleData) => {
  try {
    return await apiFetch({
      path: API_BASE,
      method: 'POST',
      data: {
        ...ruleData,
        status: 'publish',
      },
    });
  } catch (error) {
    console.error('Error creating rule:', error);
    throw error;
  }
};

/**
 * Update an existing rule
 */
export const updateRule = async (ruleId, ruleData) => {
  try {
    return await apiFetch({
      path: `${API_BASE}/${ruleId}`,
      method: 'POST',
      data: {
        ...ruleData,
        status: 'publish',
      },
    });
  } catch (error) {
    console.error('Error updating rule:', error);
    throw error;
  }
};

/**
 * Delete a rule
 */
export const deleteRule = async (ruleId) => {
  try {
    return await apiFetch({
      path: `${API_BASE}/${ruleId}`,
      method: 'DELETE',
    });
  } catch (error) {
    console.error('Error deleting rule:', error);
    throw error;
  }
};