import { cookies, headers } from "next/headers";
import type { AppConfig } from "next-intl";
import { getRequestConfig } from "next-intl/server";
import { allMessages } from "../../messages";

const locales = ["en", "de"];

declare module "next-intl" {
  interface AppConfig {
    Locale: (typeof locales)[number];
    Messages: typeof allMessages.en;
    // Formats: typeof formats;
  }
}

const getPreferredLocale = async () => {
  const h = await headers();
  const header = h.get("accept-language");
  if (!header) return "en"; // Fallback

  // Beispiel: "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7"
  const languages = header.split(",").map((lang) => {
    const [code, qValue] = lang.trim().split(";q=");
    return { code, q: qValue ? parseFloat(qValue) : 1.0 };
  });

  // Nach Qualität sortieren
  languages.sort((a, b) => b.q - a.q);

  // Nur den Sprachcode, kein Regionssuffix
  const top = languages[0]?.code?.split("-")[0] ?? "en";
  return top;
};

export default getRequestConfig(async () => {
  const store = await cookies();
  const locale: AppConfig["Locale"] =
    store.get("locale")?.value || (await getPreferredLocale());
  const messages: AppConfig["Messages"] =
    locale === "de" ? allMessages.de : allMessages.en;
  return {
    locale,
    messages,
  };
});
