import type { RequestHandler } from './$types';
import {
	centrawarungJson,
	centrawarungOptionsResponse,
	centrawarungServerError,
	ensureKodeposDataAvailable,
	guardCentrawarungGet
} from '$lib/server/centrawarung-api';
import { getProvinsiList } 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;

	try {
		const data = await getProvinsiList();
		return centrawarungJson({
			success: true,
			total: data.length,
			data
		});
	} catch {
		return centrawarungServerError('Gagal mengambil data provinsi.');
	}
};

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