/*
  SEO helpers (SEO_SPEC). hreflang alternates and the sitemap derive from the slug
  map (ARCHITECTURE A5), so they can never drift from the routes.
*/

import { LOCALES, HREFLANG, HTML_LANG, DEFAULT_LOCALE, type Locale } from '@i18n/locales';
import { pathFor, type PageId } from '@i18n/slugMap';
import { getProfile } from '@lib/content';

export function absUrl(path: string, origin: string): string {
  return new URL(path, origin).href;
}

/** hreflang alternates for a page: en, nb, and x-default → en (SEO_SPEC §2). */
export function alternates(pageId: PageId, origin: string) {
  const list = LOCALES.map((l) => ({
    hreflang: HREFLANG[l],
    href: absUrl(pathFor(pageId, l), origin),
  }));
  list.push({ hreflang: 'x-default', href: absUrl(pathFor(pageId, DEFAULT_LOCALE), origin) });
  return list;
}

export function ogImagePath(pageId: PageId, locale: Locale): string {
  return `/og/${pageId}-${locale}.png`;
}

const JOB_TITLE: Record<Locale, string> = { en: 'Systems Developer', no: 'Systemutvikler' };

/** JSON-LD graph for a page (SEO_SPEC §3). */
export function buildJsonLd(
  pageId: PageId,
  locale: Locale,
  origin: string,
  opts: { projectName?: string; projectType?: 'SoftwareApplication' | 'SoftwareSourceCode' } = {},
): object[] {
  const p = getProfile(locale);
  const graph: object[] = [];

  const person = {
    '@context': 'https://schema.org',
    '@type': 'Person',
    name: p.name,
    jobTitle: JOB_TITLE[locale],
    url: absUrl(pathFor('home', locale), origin),
    email: `mailto:${p.links.email}`,
    address: {
      '@type': 'PostalAddress',
      addressLocality: 'Tønsberg',
      addressCountry: 'NO',
    },
    sameAs: [p.links.linkedin],
    knowsLanguage: ['en', 'nb'],
    knowsAbout: ['C#', '.NET', 'React', 'TypeScript', 'Python', 'SQL', 'Docker', 'Linux'],
  };

  if (pageId === 'home') {
    graph.push(person);
    graph.push({
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: p.name,
      url: absUrl(pathFor('home', locale), origin),
      inLanguage: HTML_LANG[locale],
    });
  } else if (opts.projectName) {
    graph.push({
      '@context': 'https://schema.org',
      '@type': opts.projectType ?? 'CreativeWork',
      name: opts.projectName,
      author: person,
      inLanguage: HTML_LANG[locale],
      url: absUrl(pathFor(pageId, locale), origin),
    });
  } else {
    // Breadcrumb for other inner pages.
    graph.push({
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      itemListElement: [
        {
          '@type': 'ListItem',
          position: 1,
          name: p.name,
          item: absUrl(pathFor('home', locale), origin),
        },
        { '@type': 'ListItem', position: 2, item: absUrl(pathFor(pageId, locale), origin) },
      ],
    });
  }
  return graph;
}
