import type { ProductSummaryDto } from '@/lib/api';
import { absoluteUrl, SITE_NAME, SITE_URL } from '@/lib/seo';

export type JsonLd = Readonly<Record<string, unknown>>;

export function organizationJsonLd(): JsonLd {
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: SITE_NAME,
    url: SITE_URL,
  };
}

export function breadcrumbJsonLd(items: ReadonlyArray<{ name: string; path: string }>): JsonLd {
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.name,
      item: absoluteUrl(item.path),
    })),
  };
}

export function productJsonLd(product: ProductSummaryDto): JsonLd {
  const image = product.images?.find((item) => item.role === 'main') ?? product.images?.[0];
  return withoutUndefined({
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.name,
    description: product.description ?? product.seoDescription ?? undefined,
    url: absoluteUrl(product.url),
    image: image ? absoluteCatalogUrl(image.url) : undefined,
    sku: product.slug,
  });
}

export function JsonLdScript({ data }: Readonly<{ data: JsonLd | readonly JsonLd[] }>) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, '\\u003c') }}
    />
  );
}

function absoluteCatalogUrl(value: string): string {
  return URL.canParse(value) ? value : absoluteUrl(value);
}

function withoutUndefined(input: JsonLd): JsonLd {
  return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
}
