import "server-only";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { FALLBACK_LOCALES, type SupportedLocale } from "@/app/lib/i18n/locales";
/**
* Fetches the DB-driven locale registry for the admin portal (admin -> /api/admin/locales, the
* full registry including disabled rows so staging text can be entered before a locale is
* enabled) and returns it as display entries.
*
*
Fallback floor: any failure — no session on a public page (401), an unreachable upstream,
* or an empty list — degrades to {@link FALLBACK_LOCALES} (en_US + zh_CN), NEVER an empty
* list, so the language switcher can never render empty.
*/
export async function loadRuntimeLocales(): Promise {
const token = await getToken();
// No session (login page): /api/admin/locales needs a JWT, so read the public enabled-only list.
const result = token
? await callMobileApi("/api/admin/locales", { token })
: await callMobileApi("/api/public/locales");
if (!result.ok || !Array.isArray(result.data)) {
return FALLBACK_LOCALES;
}
const locales: SupportedLocale[] = [];
for (const row of result.data) {
if (row && typeof row === "object") {
const r = row as { code?: unknown; label?: unknown; enabled?: unknown };
if (typeof r.code === "string" && r.code && typeof r.label === "string") {
// Carry the enabled flag through so the switcher can hide disabled rows
// while the /messages editor still sees them. Only an explicit `false`
// hides; a missing flag is treated as enabled.
locales.push({ code: r.code, label: r.label, enabled: r.enabled !== false });
}
}
}
return locales.length > 0 ? locales : FALLBACK_LOCALES;
}