import { getSupabase } from '$lib/supabase';

export type SearchResultType = 'shopping_item' | 'task' | 'note';

export interface SearchRow {
	id: string;
	result_type: SearchResultType;
	title: string | null;
	snippet: string;
	collective_id: string;
	list_id: string | null;
	created_by: string;
	created_at: string;
	rank: number;
}

export interface SearchFilters {
	types?: SearchResultType[];
	creator?: string;
	from?: string;
	to?: string;
}

export async function runSearch(
	collectiveId: string,
	query: string,
	filters: SearchFilters = {}
): Promise<SearchRow[]> {
	const { data, error } = await getSupabase().rpc('search_in_collective' as never, {
		p_collective_id: collectiveId,
		p_query: query,
		p_types: filters.types ?? null,
		p_creator: filters.creator ?? null,
		p_from: filters.from ?? null,
		p_to: filters.to ?? null
	} as never);
	if (error) return [];
	return (data ?? []) as unknown as SearchRow[];
}
