import type { RequestHandler } from './$types';
import {
	centrawarungBadRequest,
	centrawarungJson,
	centrawarungOptionsResponse,
	centrawarungServerError,
	ensureKodeposDataAvailable,
	guardCentrawarungGet
} from '$lib/server/centrawarung-api';
import { getKotaByProvinsi } from '$lib/server/referensi';

export const GET: RequestHandler = async (event) => {
	const authError = await guardCentrawarungGet(event);
	if (authError) return authError;

	const kodeposError = await ensureKodeposDataAvailable();
	if (kodeposError) return kodeposError;

	const provinsi = event.url.searchParams.get('provinsi')?.trim();
	if (!provinsi) {
		return centrawarungBadRequest('Parameter provinsi wajib diisi.');
	}

	try {
		const rows = await getKotaByProvinsi(provinsi);
		const data = rows.map((row) => ({
			nama: row.nama,
			kabupaten: row.nama
		}));

		return centrawarungJson({
			success: true,
			provinsi,
			total: data.length,
			data
		});
	} catch {
		return centrawarungServerError('Gagal mengambil data kota/kabupaten.');
	}
};

export const OPTIONS: RequestHandler = async () => centrawarungOptionsResponse();
