export interface RestaurantTable {
  id: string;
  restaurant_id: string;
  branch_id: string;
  table_number: string;
  label: string | null;
  capacity: number;
  zone: string | null;
  qr_style_json: Record<string, unknown>;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

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 listTables(branchId?: string): Promise<{ tables: RestaurantTable[] }> {
  const qs = branchId ? `?branch_id=${encodeURIComponent(branchId)}` : '';
  return apiFetch<{ tables: RestaurantTable[] }>(`/api/tables${qs}`);
}

export async function createTable(body: Partial<RestaurantTable> & { branch_id: string; table_number: string }): Promise<{ table: RestaurantTable }> {
  return apiFetch<{ table: RestaurantTable }>('/api/tables', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function bulkCreateTables(body: { branch_id: string; start: number; end: number; prefix?: string; capacity?: number; zone?: string }) {
  return apiFetch<{ tables: RestaurantTable[]; created: number; requested: number }>('/api/tables', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function updateTable(id: string, body: Partial<RestaurantTable>): Promise<{ table: RestaurantTable }> {
  return apiFetch<{ table: RestaurantTable }>(`/api/tables/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function deleteTable(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/tables/${id}`, { method: 'DELETE' });
}
