import type { BobbinContext, XrpcRequestInit } from "./client";
import { jsonGet } from "./_request";
import { paginateBy } from "./pagination";

export interface SearchHit {
	uri: string;
	cid?: string;
	nsid: string;
	score: number;
	/** the indexed record; shape varies by `nsid`. */
	value: unknown;
}

export interface SearchPage {
	hits: SearchHit[];
	cursor: string | null;
}

export interface SearchParams {
	q: string;
	nsid?: string;
	author?: string;
	repo?: string;
	since?: string;
	until?: string;
	cursor?: string;
	limit?: number;
}

export const search = (ctx: BobbinContext, params: SearchParams, init?: XrpcRequestInit) =>
	jsonGet<SearchPage>(ctx, "sh.tangled.search.query", { ...params }, init);

export interface SearchAllOptions extends XrpcRequestInit {
	maxPages?: number;
}

/** Async-iterate every search hit across cursor pages. */
export async function* searchAll(
	ctx: BobbinContext,
	params: Omit<SearchParams, "cursor">,
	options: SearchAllOptions = {}
): AsyncGenerator<SearchHit, void, unknown> {
	yield* paginateBy<SearchHit>(async (cursor) => {
		const page = await search(ctx, { ...params, cursor }, options);
		return { items: page.hits, cursor: page.cursor };
	}, options);
}
