import { cookies, headers } from "next/headers";
import type { Metadata } from "next";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { resolveServerLanguage } from "./index";
import type { SeoPageKey } from "./resources";
import { getSeoPage } from "./seo";
import type { AppLanguage } from "./registry";

export async function getServerLanguage(): Promise<AppLanguage> {
  const cookieStore = await cookies();
  const headerStore = await headers();
  return resolveServerLanguage({
    cookieStore,
    acceptLanguage: headerStore.get("accept-language"),
  });
}

type SeoPageMetadataOptions = {
  lang?: AppLanguage;
  path?: string;
  title?: string;
  description?: string;
  keywords?: string[];
  appendSiteName?: boolean;
  index?: boolean;
  type?: "website" | "article" | "profile";
  imageUrl?: string;
  imageAlt?: string;
  ogTitle?: string;
  publishedTime?: string;
  modifiedTime?: string;
};

/** Server helper: metadata for a registered SEO page key + cookie/header locale */
export async function generateSeoPageMetadata(
  pageKey: SeoPageKey,
  options: SeoPageMetadataOptions = {}
): Promise<Metadata> {
  const lang = options.lang ?? (await getServerLanguage());
  const page = getSeoPage(pageKey, lang);

  return generatePageMetadata({
    title: options.title ?? page.title,
    description: options.description ?? page.description,
    path: options.path ?? page.path,
    keywords: options.keywords ?? page.keywords,
    appendSiteName: options.appendSiteName ?? false,
    index: options.index,
    type: options.type,
    imageUrl: options.imageUrl,
    imageAlt: options.imageAlt,
    ogTitle: options.ogTitle,
    publishedTime: options.publishedTime,
    modifiedTime: options.modifiedTime,
    lang,
  });
}
