import { baseAPI } from "@/lib/api";

type ApiResponse<T> = {
  success: boolean;
  statusCode: number;
  message: string;
  data: T;
};

// The kinds of record the search can return, in the order the dropdown shows
// them.
export type SearchGroup =
  | "issues"
  | "progressReports"
  | "meetings"
  | "plenary";

export type SearchResult = {
  group: SearchGroup;
  id: number;
  title: string;
  subtitle?: string;
  // The ids the link is built from; the API never guesses a route.
  meta?: Record<string, string | number>;
};

export type SearchResponse = {
  query: string;
  results: SearchResult[];
};

export async function getGlobalSearch(
  query: string,
  limit = 5,
): Promise<SearchResponse> {
  const params = new URLSearchParams({ q: query, limit: String(limit) });
  const response = (await baseAPI(
    `/search?${params.toString()}`,
  )) as ApiResponse<SearchResponse>;

  return response.data ?? { query, results: [] };
}
