import { apiRequest } from "./client";
import { arr } from "../utils/normalizers";

export type SearchParams = {
  keyword?: string;
  q?: string;
  types?: string;
  page?: number;
  pageSize?: number;
};

export type SearchResult = {
  q?: string;
  page?: number;
  pageSize?: number;
  total?: number;
  totalByType?: Record<string, number>;
  items: any[];
};

export function searchAll(params: SearchParams): Promise<SearchResult> {
  const query = new URLSearchParams();
  const keyword = String(params.q || params.keyword || "").trim();
  if (keyword) query.set("q", keyword);
  if (params.types) query.set("types", params.types);
  query.set("page", String(params.page || 1));
  query.set("pageSize", String(params.pageSize || 20));

  return apiRequest(`/api/search?${query.toString()}`).then((data) => ({
    ...(data || {}),
    items: arr(data?.items || data)
  }));
}
