async function fetchApi(path: string, options?: RequestInit) {
  const res = await fetch(path, { credentials: 'include', ...options });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

export async function getAdminDashboard() {
  return fetchApi('/api/admin/dashboard');
}

export async function getAdminAnalytics() {
  return fetchApi('/api/admin/analytics');
}

export async function getAdminRestaurants() {
  return fetchApi('/api/admin/restaurants');
}

export async function getAdminSupport(params?: { search?: string; severity?: string }) {
  const sp = new URLSearchParams();
  if (params?.search) sp.set('search', params.search);
  if (params?.severity) sp.set('severity', params.severity);
  const qs = sp.toString();
  return fetchApi(`/api/admin/support${qs ? `?${qs}` : ''}`);
}

export async function getAdminBilling() {
  return fetchApi('/api/admin/billing');
}

export async function getAdminBillingPlansAll() {
  return fetchApi('/api/admin/billing/plans');
}

export async function getAdminBillingPlan(id: string) {
  return fetchApi(`/api/admin/billing/plans/${id}`);
}

export async function createAdminBillingPlan(payload: Record<string, unknown>) {
  return fetchApi('/api/admin/billing/plans', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
}

export async function updateAdminBillingPlan(id: string, payload: Record<string, unknown>) {
  return fetchApi(`/api/admin/billing/plans/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
}

export async function deleteAdminBillingPlan(id: string) {
  return fetchApi(`/api/admin/billing/plans/${id}`, { method: 'DELETE' });
}

export async function getAdminAiSettings() {
  return fetchApi('/api/admin/ai-settings');
}

export async function saveAdminAiSettings(settings: Record<string, unknown>) {
  return fetchApi('/api/admin/ai-settings', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ settings }),
  });
}

export async function syncAdminBillingPlan(id: string) {
  return fetchApi(`/api/admin/billing/plans/${id}/sync`, { method: 'POST' });
}
