import "server-only";
import { cookies, headers } from "next/headers";
import { DEFAULT_LANG, LANG_COOKIE, type Lang } from "@/config/constants";
import ar from "@/locales/ar.json";
import en from "@/locales/en.json";

export const LANG_HEADER = "x-ivory-lang";

const isLang = (v?: string | null): v is Lang => v === "ar" || v === "en";

/**
 * لغة الطلب الحالي على الخادم:
 *   1) ?lang=en|ar في الرابط (يضبطها middleware.ts في ترويسة x-ivory-lang)
 *   2) Cookie المحفوظة عند تبديل اللغة
 *   3) العربية افتراضياً — نفس الافتراض في المشروع الأصلي
 */
export async function getLang(): Promise<Lang> {
    const h = await headers();
    const fromHeader = h.get(LANG_HEADER);
    if (isLang(fromHeader)) return fromHeader;
    const c = await cookies();
    const fromCookie = c.get(LANG_COOKIE)?.value;
    return isLang(fromCookie) ? fromCookie : DEFAULT_LANG;
}

const dict = { ar, en } as Record<Lang, Record<string, any>>;

/** ترجمة على الخادم بنفس مفاتيح i18next الأصلية (فاصل المفاتيح ".") */
export function t(lang: Lang, key: string): string {
    const walk = (obj: any) => key.split(".").reduce((o, k) => (o == null ? undefined : o[k]), obj);
    const v = walk(dict[lang]) ?? walk(dict[DEFAULT_LANG]);
    return typeof v === "string" ? v : key;
}
