import "server-only";

import { SITE } from "./site";

/** Absolute site URL for canonicals, sitemap and structured data. */
export function siteUrl(): string {
  return (
    process.env.NEXT_PUBLIC_SITE_URL?.replace(/\/+$/, "") || SITE.url
  );
}

export function absoluteUrl(path: string): string {
  return `${siteUrl()}${path.startsWith("/") ? path : `/${path}`}`;
}

interface BreadcrumbItem {
  name: string;
  path: string;
}

export function websiteJsonLd() {
  return {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: SITE.name,
    url: siteUrl(),
    description: SITE.description,
    potentialAction: {
      "@type": "SearchAction",
      target: `${siteUrl()}/games?q={search_term_string}`,
      "query-input": "required name=search_term_string",
    },
  };
}

export function breadcrumbJsonLd(items: BreadcrumbItem[]) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((item, i) => ({
      "@type": "ListItem",
      position: i + 1,
      name: item.name,
      item: absoluteUrl(item.path),
    })),
  };
}

export function videoGameJsonLd(input: {
  title: string;
  description: string;
  slug: string;
  categoryName: string;
  developer?: string | null;
}) {
  return {
    "@context": "https://schema.org",
    "@type": "VideoGame",
    name: input.title,
    description: input.description,
    url: absoluteUrl(`/games/${input.slug}`),
    genre: input.categoryName,
    gamePlatform: "Web browser",
    applicationCategory: "Game",
    ...(input.developer
      ? { author: { "@type": "Organization", name: input.developer } }
      : {}),
  };
}
