import { apiFetch } from '@/api/client';

export function fetchCodeStats() {
  return apiFetch<unknown>('/api/code/api/stats');
}

export function fetchCodeFiles(limit?: number, offset?: number) {
  const params = new URLSearchParams();
  if (limit != null) params.set('limit', String(limit));
  if (offset != null) params.set('offset', String(offset));
  const qs = params.toString();
  return apiFetch<unknown>(`/api/code/api/files${qs ? `?${qs}` : ''}`);
}

export function fetchCodeEntities(q?: string, limit?: number) {
  const params = new URLSearchParams();
  if (q) params.set('q', q);
  if (limit != null) params.set('limit', String(limit));
  const qs = params.toString();
  return apiFetch<unknown>(`/api/code/api/entities${qs ? `?${qs}` : ''}`);
}

export function searchCodeEntities(q: string, limit?: number) {
  const params = new URLSearchParams({ q });
  if (limit != null) params.set('limit', String(limit));
  return apiFetch<unknown>(`/api/code/api/entities/search?${params.toString()}`);
}

export function fetchCodeGraph(limit?: number) {
  const params = new URLSearchParams();
  if (limit != null) params.set('limit', String(limit));
  const qs = params.toString();
  return apiFetch<unknown>(`/api/code/api/graph${qs ? `?${qs}` : ''}`);
}

export function fetchCodeTree(prefix?: string) {
  const params = new URLSearchParams();
  if (prefix) params.set('prefix', prefix);
  const qs = params.toString();
  return apiFetch<unknown>(`/api/code/api/tree${qs ? `?${qs}` : ''}`);
}

export function fetchCodeGraphSampled(limit?: number) {
  const params = new URLSearchParams();
  if (limit != null) params.set('limit', String(limit));
  const qs = params.toString();
  return apiFetch<unknown>(`/api/code/api/graph/sampled${qs ? `?${qs}` : ''}`);
}

export function fetchCodeGraphNeighborhood(entityName: string, depth?: number, maxNodes?: number) {
  const params = new URLSearchParams({ entity_name: entityName });
  if (depth != null) params.set('depth', String(depth));
  if (maxNodes != null) params.set('max_nodes', String(maxNodes));
  return apiFetch<unknown>(`/api/code/api/graph/neighborhood?${params.toString()}`);
}
