/**
 * Shared fetch helper for admin-web pages that call proxy API routes.
 * Automatically injects Authorization + x-product-id headers from localStorage.
 */

function getAuthHeaders(): Record<string, string> {
  if (typeof window === 'undefined') return {};
  const headers: Record<string, string> = {};
  const token = localStorage.getItem('admin_access_token');
  if (token) headers['Authorization'] = `Bearer ${token}`;
  const productId = localStorage.getItem('admin_selected_product');
  if (productId) headers['x-product-id'] = productId;
  return headers;
}

/**
 * Creates a scoped fetch helper for a given proxy base path.
 *
 * Usage:
 *   const apiFetch = createProxyFetch('/api/jobs');
 *   const data = await apiFetch('list');          // GET /api/jobs/list
 *   await apiFetch('123', { method: 'PUT', body: ... });
 */
export function createProxyFetch(basePath: string) {
  return async function proxyFetch(path: string, opts?: RequestInit) {
    const url = !path || path.startsWith('?') ? `${basePath}${path}` : `${basePath}/${path}`;
    const res = await fetch(url, {
      ...opts,
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders(),
        ...opts?.headers,
      },
    });
    return res.json();
  };
}
