import type { Metadata } from "next";
import { settingValue } from "@/lib/settings";

/**
 * Build Next.js Metadata.openGraph + Metadata.twitter for an article.
 * Port of Rank Math's includes/opengraph/* and twitter/* PHP modules.
 *
 * Site-wide defaults come from the Setting table (site.title, site.description,
 * social.facebook, social.twitter, …); per-article overrides win.
 */

export interface ArticleSocialInput {
  url: string;
  title: string;
  description: string;
  image?: string | null;
  imageAlt?: string | null;
  publishedAt?: Date | null;
  updatedAt?: Date | null;
  authorName?: string | null;
  categoryName?: string | null;
  tagNames?: string[];
  isNews?: boolean;
}

export async function buildArticleSocial(
  input: ArticleSocialInput,
): Promise<Pick<Metadata, "openGraph" | "twitter">> {
  const siteName = (await settingValue("site.title")) ?? "Finzone Network";
  const twitterHandle = (await settingValue("social.twitter")) ?? "";
  const fallbackImage = (await settingValue("seo.default_image")) ?? "";
  const image = input.image || fallbackImage || undefined;

  return {
    openGraph: {
      type: "article",
      url: input.url,
      title: input.title,
      description: input.description,
      siteName,
      locale: "vi_VN",
      ...(image
        ? {
            images: [
              {
                url: image,
                width: 1200,
                height: 630,
                alt: input.imageAlt ?? input.title,
              },
            ],
          }
        : {}),
      publishedTime: input.publishedAt?.toISOString(),
      modifiedTime: input.updatedAt?.toISOString(),
      authors: input.authorName ? [input.authorName] : undefined,
      section: input.categoryName ?? undefined,
      tags: input.tagNames,
    },
    twitter: {
      card: image ? "summary_large_image" : "summary",
      title: input.title,
      description: input.description,
      ...(image ? { images: [image] } : {}),
      ...(twitterHandle
        ? {
            site: twitterHandle.startsWith("@") ? twitterHandle : `@${twitterHandle}`,
            creator: twitterHandle.startsWith("@") ? twitterHandle : `@${twitterHandle}`,
          }
        : {}),
    },
  };
}
