import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';

/**
 * GET /api/search?q=<query>
 * Proxies to the Go backend's /api/search endpoint.
 * Returns: { results, local_count, remote_count }
 *
 * Response shape mirrors SearchResponse in the iOS APIClient.
 */
export const GET: RequestHandler = async ({ url }) => {
	const q = url.searchParams.get('q') ?? '';

	if (q.trim().length < 2) {
		return json({ results: [], local_count: 0, remote_count: 0 });
	}

	const apiURL = `/api/search?q=${encodeURIComponent(q.trim())}`;
	try {
		const res = await backendFetch(apiURL);
		if (!res.ok) {
			log.error('api/search', 'backend returned error', { status: res.status, q });
			error(502, `Search failed: ${res.status}`);
		}
		const data = await res.json();
		return json(data);
	} catch (e) {
		if (e instanceof Error && 'status' in e) throw e;
		log.error('api/search', 'network error', { q, err: String(e) });
		error(502, 'Could not reach backend');
	}
};
