/**
 * API helper functions for the wizard
 *
 * All endpoints use the REST API namespace wahrb/v1
 * and authenticate via the WP nonce.
 */

const getConfig = () => window.wahrbWizardConfig || {};
const getHeaders = () => ({
  'Content-Type': 'application/json',
  'X-WP-Nonce': getConfig().nonce,
});

/**
 * Fetch wizard settings
 */
export async function fetchWizardSettings() {
  const response = await fetch(`${getConfig().apiUrl}/vendor/wizard/settings`, {
    headers: getHeaders(),
  });
  if (!response.ok) throw new Error('Failed to fetch settings');
  return response.json();
}

/**
 * Fetch existing draft
 */
export async function fetchDraft(productId) {
  const url = new URL(`${getConfig().apiUrl}/vendor/wizard/draft`);
  if (productId) url.searchParams.set('product_id', productId);
  const response = await fetch(url, { headers: getHeaders() });
  if (!response.ok) throw new Error('Failed to fetch draft');
  return response.json();
}

/**
 * Save draft data
 */
export async function saveDraft(data) {
  const response = await fetch(`${getConfig().apiUrl}/vendor/wizard/draft`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(data),
  });
  if (response.status === 409) {
    const err = new Error('VERSION_CONFLICT');
    err.status = 409;
    throw err;
  }
  if (!response.ok) {
    let msg = 'Failed to save draft';
    try {
      const body = await response.json();
      if (body.message) msg = body.message;
    } catch (e) { /* ignore parse error */ }
    const err = new Error(msg);
    err.status = response.status;
    throw err;
  }
  return response.json();
}

/**
 * Publish the offer
 */
export async function publishOffer(data) {
  const response = await fetch(`${getConfig().apiUrl}/vendor/wizard/publish`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(data),
  });
  if (!response.ok) throw new Error('Failed to publish');
  return response.json();
}

/**
 * Fetch vendor products
 */
export async function getProducts(search = '') {
  const url = new URL(`${getConfig().apiUrl}/vendor/wizard/products`);
  if (search) url.searchParams.set('search', search);
  const response = await fetch(url, { headers: getHeaders() });
  if (!response.ok) throw new Error('Failed to fetch products');
  return response.json();
}

/**
 * Calculate price preview
 */
export async function getPricePreview(data) {
  const response = await fetch(`${getConfig().apiUrl}/vendor/wizard/price-preview`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(data),
  });
  if (!response.ok) throw new Error('Failed to calculate preview');
  return response.json();
}

/**
 * Upload file
 */
export async function uploadFile(file) {
  const formData = new FormData();
  formData.append('file', file);
  const response = await fetch(`${getConfig().apiUrl}/vendor/wizard/upload`, {
    method: 'POST',
    headers: { 'X-WP-Nonce': getConfig().nonce },
    body: formData,
  });
  if (!response.ok) throw new Error('Failed to upload file');
  return response.json();
}

/**
 * Fetch blackout dates for a product
 */
export async function getBlackouts(productId) {
  const response = await fetch(
    `${getConfig().apiUrl}/vendor/blackouts?product_id=${productId}`,
    { headers: getHeaders() }
  );
  if (!response.ok) throw new Error('Failed to fetch blackouts');
  return response.json();
}

/**
 * Add blackout date range
 */
export async function addBlackout(data) {
  const response = await fetch(`${getConfig().apiUrl}/vendor/blackouts`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(data),
  });
  if (!response.ok) throw new Error('Failed to add blackout');
  return response.json();
}

/**
 * Delete a blackout period
 */
export async function deleteBlackout(id) {
  const response = await fetch(`${getConfig().apiUrl}/vendor/blackouts/${id}`, {
    method: 'DELETE',
    headers: getHeaders(),
  });
  if (!response.ok) throw new Error('Failed to delete blackout');
  return response.json();
}
