import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { hasKodeposData, searchKodepos } from '$lib/server/referensi';

export const GET: RequestHandler = async ({ url }) => {
	const q = url.searchParams.get('q')?.trim() ?? '';

	if (q.length < 2) {
		return json({ success: false, message: 'Ketik minimal 2 karakter untuk mencari.' }, { status: 400 });
	}

	if (!(await hasKodeposData())) {
		return json(
			{ success: false, message: 'Data kodepos belum diimpor. Jalankan: npm run db:kodepos' },
			{ status: 503 }
		);
	}

	try {
		const data = await searchKodepos(q);
		return json({ success: true, data });
	} catch {
		return json({ success: false, message: 'Gagal mencari data kodepos.' }, { status: 500 });
	}
};
