import { request, BASE } from "./client";

// ── Types ────────────────────────────────────────────────────────────────────

export interface SearchResultItem {
  title: string;
  slug: string;
  type: string;
  score: number;
  summary: string;
  creator_name: string;
  creator_slug: string;
  topic_category: string;
  topic_tags: string[];
  technique_page_slug?: string;
  match_context?: string;
  section_anchor?: string;
  section_heading?: string;
}

export interface SearchResponse {
  items: SearchResultItem[];
  partial_matches: SearchResultItem[];
  total: number;
  query: string;
  fallback_used: boolean;
}

export interface SuggestionItem {
  text: string;
  type: "topic" | "technique" | "creator";
}

export interface SuggestionsResponse {
  suggestions: SuggestionItem[];
}

export interface PopularSearchItem {
  query: string;
  count: number;
}

export interface PopularSearchesResponse {
  items: PopularSearchItem[];
  cached: boolean;
}

// ── Functions ────────────────────────────────────────────────────────────────

export async function fetchSuggestions(): Promise<SuggestionsResponse> {
  return request<SuggestionsResponse>(`${BASE}/search/suggestions`);
}

export async function searchApi(
  q: string,
  scope?: string,
  limit?: number,
  sort?: string,
): Promise<SearchResponse> {
  const qs = new URLSearchParams({ q });
  if (scope) qs.set("scope", scope);
  if (limit !== undefined) qs.set("limit", String(limit));
  if (sort) qs.set("sort", sort);
  return request<SearchResponse>(`${BASE}/search?${qs.toString()}`);
}

export async function fetchPopularSearches(): Promise<PopularSearchesResponse> {
  return request<PopularSearchesResponse>(`${BASE}/search/popular`);
}
