/**
 * Middleware: lädt Übersetzungen aus der CMS-API (translation_bundle) und setzt Astro.locals.translations.
 * Single source of truth: API des Servers.
 */
import { defineMiddleware } from "astro:middleware";
import { getTranslationBundleBySlug } from "./lib/cms";
import { TRANSLATION_BUNDLE_SLUG } from "./lib/constants";
import { resetCmsFromCache } from "./lib/cms-cache-state";

export const onRequest = defineMiddleware(async (context, next) => {
  resetCmsFromCache();
  let translations: Record<string, string> = {};
  try {
    const bundle = await getTranslationBundleBySlug(TRANSLATION_BUNDLE_SLUG, {
      locale: "de",
    });
    if (bundle?.strings && typeof bundle.strings === "object") {
      const normalized: Record<string, string> = {};
      for (const [key, val] of Object.entries(bundle.strings)) {
        const v = val as unknown;
        const str =
          typeof v === "string"
            ? v
            : typeof v === "object" && v !== null && "value" in v
              ? (v as { value?: unknown }).value
              : (v as { text?: unknown })?.text ?? (v as { label?: unknown })?.label;
        if (typeof str === "string") normalized[key] = str;
      }
      translations = { ...normalized };
    }
  } catch {
    /* CMS nicht erreichbar */
  }
  context.locals.translations = translations;
  return next();
});
