/**
 * JSON-LD schema.org helpers for SEO. Keep output minimal and stable —
 * Google's rich-result validator is strict about required fields.
 *
 * Usage:
 *   const siteUrl = await getSetting("site.url");
 *   <script type="application/ld+json"
 *     dangerouslySetInnerHTML={{ __html: jsonLdScript(buildOrganization(siteUrl)) }}/>
 *
 * NOTE: All builders take siteUrl as the first arg so the value can come
 * from runtime DB settings (lib/settings.ts) instead of build-time env.
 * This lets admins change the public domain without a rebuild.
 */

const SITE_NAME = "Tử Vi Số";

export function buildOrganization(siteUrl: string) {
  return {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: SITE_NAME,
    url: siteUrl,
    logo: `${siteUrl}/icon-512.png`,
    sameAs: [],
  };
}

export function buildWebsite(siteUrl: string) {
  return {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: SITE_NAME,
    url: siteUrl,
    inLanguage: "vi-VN",
    potentialAction: {
      "@type": "SearchAction",
      target: `${siteUrl}/blog?q={search_term_string}`,
      "query-input": "required name=search_term_string",
    },
  };
}

export function buildBreadcrumbs(siteUrl: string, items: Array<{ name: string; href: string }>) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((it, idx) => ({
      "@type": "ListItem",
      position: idx + 1,
      name: it.name,
      item: it.href.startsWith("http") ? it.href : `${siteUrl}${it.href}`,
    })),
  };
}

export function buildArticle(
  siteUrl: string,
  input: {
    headline: string;
    description: string;
    slug: string;
    publishedAt: Date | string;
    updatedAt?: Date | string | null;
    authorName?: string;
    imageUrl?: string;
    category?: string;
  }
) {
  const url = `${siteUrl}/blog/${input.slug}`;
  return {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: input.headline,
    description: input.description,
    url,
    mainEntityOfPage: { "@type": "WebPage", "@id": url },
    datePublished: new Date(input.publishedAt).toISOString(),
    ...(input.updatedAt ? { dateModified: new Date(input.updatedAt).toISOString() } : {}),
    author: {
      "@type": "Organization",
      name: input.authorName ?? SITE_NAME,
    },
    publisher: {
      "@type": "Organization",
      name: SITE_NAME,
      logo: { "@type": "ImageObject", url: `${siteUrl}/icon-512.png` },
    },
    ...(input.imageUrl ? { image: input.imageUrl } : {}),
    ...(input.category ? { articleSection: input.category } : {}),
    inLanguage: "vi-VN",
  };
}

export function buildSoftwareApp(
  siteUrl: string,
  input: { name: string; description: string; slug: string }
) {
  return {
    "@context": "https://schema.org",
    "@type": "WebApplication",
    name: input.name,
    description: input.description,
    url: `${siteUrl}/${input.slug}`,
    applicationCategory: "LifestyleApplication",
    operatingSystem: "Any",
    offers: { "@type": "Offer", price: "0", priceCurrency: "VND" },
    inLanguage: "vi-VN",
  };
}

/**
 * Inline-renderable JSON-LD <script> string. Returns markup-safe string.
 * Caller injects with dangerouslySetInnerHTML.
 */
export function jsonLdScript(data: unknown): string {
  return JSON.stringify(data).replace(/</g, "\\u003c");
}
