export interface AlertSettings {
  soundEnabled: boolean;
  volume: number;
  autoDismiss: number;
  showOrders: boolean;
  showBookings: boolean;
  showAiEscalations: boolean;
  browserNotifications: boolean;
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function getAlertSettings(): Promise<AlertSettings> {
  const data = await apiFetch<{ settings: AlertSettings }>('/api/alert-settings');
  return data.settings;
}

export async function saveAlertSettings(settings: AlertSettings): Promise<AlertSettings> {
  const data = await apiFetch<{ settings: AlertSettings }>('/api/alert-settings', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(settings),
  });
  return data.settings;
}

export async function getAdminAlertSettings(restaurantId: string): Promise<AlertSettings> {
  const data = await apiFetch<{ settings: AlertSettings }>(`/api/admin/alert-settings?restaurantId=${encodeURIComponent(restaurantId)}`);
  return data.settings;
}

export async function saveAdminAlertSettings(restaurantId: string, settings: AlertSettings): Promise<AlertSettings> {
  const data = await apiFetch<{ settings: AlertSettings }>('/api/admin/alert-settings', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ restaurantId, ...settings }),
  });
  return data.settings;
}
