import type { RequestHandler } from './$types';
import {
	centrawarungJson,
	centrawarungNotFound,
	centrawarungOptionsResponse,
	centrawarungServerError,
	getTblKodeposByIdForCentrawarung,
	guardCentrawarungGet
} from '$lib/server/centrawarung-api';

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

	try {
		const id = Number(event.params.id);
		if (!Number.isFinite(id) || id <= 0) {
			return centrawarungNotFound('ID kodepos tidak valid.');
		}

		const data = await getTblKodeposByIdForCentrawarung(id);
		if (!data) return centrawarungNotFound('Data kodepos tidak ditemukan.');
		return centrawarungJson({ success: true, data });
	} catch {
		return centrawarungServerError('Gagal mengambil data kodepos.');
	}
};

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