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

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

	if (!provinsi) {
		return json({ success: false, message: 'Parameter provinsi wajib diisi.' }, { 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 getKotaByProvinsi(provinsi);
		return json({ success: true, data });
	} catch {
		return json({ success: false, message: 'Gagal mengambil data kota/kabupaten.' }, { status: 500 });
	}
};
