/**
 * HTTP client for the TrueRef REST API.
 *
 * Configurable via the TRUEREF_API_URL environment variable.
 * Defaults to http://localhost:5173 when not set.
 */

export const API_BASE = process.env.TRUEREF_API_URL ?? 'http://localhost:5173';

export interface ApiResponse {
	ok: boolean;
	status: number;
	statusText: string;
	text: () => Promise<string>;
}

/**
 * Call GET /api/v1/libs/search
 *
 * Returns text/plain or JSON depending on the `type` param.
 */
export async function searchLibraries(params: {
	libraryName: string;
	query: string;
	type?: 'json' | 'txt';
}): Promise<ApiResponse> {
	const url = new URL(`${API_BASE}/api/v1/libs/search`);
	url.searchParams.set('libraryName', params.libraryName);
	url.searchParams.set('query', params.query);
	url.searchParams.set('type', params.type ?? 'txt');

	return fetch(url.toString());
}

/**
 * Call GET /api/v1/context
 *
 * Returns text/plain or JSON depending on the `type` param.
 */
export async function fetchContext(params: {
	libraryId: string;
	query: string;
	tokens?: number;
	type?: 'json' | 'txt';
}): Promise<ApiResponse> {
	const url = new URL(`${API_BASE}/api/v1/context`);
	url.searchParams.set('libraryId', params.libraryId);
	url.searchParams.set('query', params.query);
	url.searchParams.set('type', params.type ?? 'txt');
	if (params.tokens !== undefined) {
		url.searchParams.set('tokens', String(params.tokens));
	}

	return fetch(url.toString());
}
