import "server-only";
import type { Metadata } from "next";
import type { Lang } from "@/config/constants";
import { SITE, SITE_URL, absoluteUrl } from "./site";
import { truncate } from "./text";

export type SeoInput = {
    lang: Lang;
    /** المسار بدون النطاق، مثل /blogs/12 */
    path: string;
    /** العنوان الكامل كما كان يُكتب في document.title في نسخة Vite */
    title: string;
    description?: string;
    keywords?: string[];
    image?: string | null;
    imageAlt?: string;
    type?: "website" | "article" | "profile";
    publishedTime?: string;
    modifiedTime?: string;
    /** صفحات خاصة (الدفع، الحساب، الاستعادة) لا تُفهرس */
    noindex?: boolean;
    /** مسار مختلف لكل لغة (مثل slug البرنامج المبني من عنوانه العربي/الإنجليزي) */
    alternates?: Partial<Record<Lang, string>>;
};

/**
 * الرابط القانوني ونسخ اللغات:
 * المحتوى العربي على الرابط المجرّد (اللغة الافتراضية كما في الأصل)،
 * والإنجليزي على الرابط نفسه مع ?lang=en — بلا تغيير في بنية روابط الموقع.
 */
export function langUrl(path: string, lang: Lang) {
    const clean = path === "" ? "/" : path;
    if (lang !== "en") return absoluteUrl(clean);
    // يدعم المسارات التي تحمل معاملات مسبقاً (مثل ?page=2 في القوائم المرقّمة)
    return `${absoluteUrl(clean)}${clean.includes("?") ? "&" : "?"}lang=en`;
}

export function buildMetadata(input: SeoInput): Metadata {
    const { lang, path, title, type = "website", noindex } = input;
    const description = truncate(input.description || SITE.description[lang], 160);
    const image = input.image ? absoluteUrl(input.image) : absoluteUrl(SITE.ogImage);
    const canonical = langUrl(path, lang);

    return {
        metadataBase: new URL(SITE_URL),
        // absolute: العنوان مكتمل مسبقاً بصيغة المشروع الأصلي "الصفحة | ايفوري ..."
        title: { absolute: title },
        description,
        keywords: [...(input.keywords || []), ...SITE.keywords[lang]],
        applicationName: SITE.name[lang],
        alternates: {
            canonical,
            languages: {
                ar: langUrl(input.alternates?.ar ?? path, "ar"),
                en: langUrl(input.alternates?.en ?? path, "en"),
                "x-default": langUrl(input.alternates?.ar ?? path, "ar"),
            },
        },
        openGraph: {
            type,
            url: canonical,
            siteName: SITE.name[lang],
            title,
            description,
            locale: lang === "ar" ? "ar_SA" : "en_US",
            alternateLocale: lang === "ar" ? ["en_US"] : ["ar_SA"],
            images: [{ url: image, alt: input.imageAlt || title }],
            ...(type === "article" && input.publishedTime ? { publishedTime: input.publishedTime } : {}),
            ...(type === "article" && input.modifiedTime ? { modifiedTime: input.modifiedTime } : {}),
        },
        twitter: {
            card: "summary_large_image",
            site: SITE.twitter,
            title,
            description,
            images: [image],
        },
        robots: noindex
            ? { index: false, follow: true, googleBot: { index: false, follow: true } }
            : {
                  index: true,
                  follow: true,
                  googleBot: { index: true, follow: true, "max-image-preview": "large", "max-snippet": -1, "max-video-preview": -1 },
              },
    };
}
