import { siteUrl } from "@/lib/seo/site";

export type Locale = "de" | "en";

/**
 * Public marketing slugs, per locale.
 *
 * `internal` is the App Router folder path under `(marketing)/[locale]/`.
 * English public slugs match the folders. German public slugs are keyword
 * URLs — middleware rewrites them onto the internal folder and 301s the
 * old English slug on `/de/…` so existing links keep working.
 */
export type SeoSlugKey =
  | "ocr-receipt-scanner"
  | "expense-tracker-freelancers"
  | "expensify-alternative"
  | "lexoffice-alternative"
  | "blog/how-receipt-ocr-works"
  | "blog/receipt-scanning-vs-manual-bookkeeping"
  | "blog/receipt-to-excel-guide"
  | "blog/organize-digital-receipts"
  | "blog/simple-expense-tracking";

export type SeoRoute = {
  key: SeoSlugKey;
  internal: SeoSlugKey;
  en: string;
  de: string;
};

export const SEO_ROUTES: readonly SeoRoute[] = [
  {
    key: "ocr-receipt-scanner",
    internal: "ocr-receipt-scanner",
    en: "ocr-receipt-scanner",
    de: "beleg-ocr",
  },
  {
    key: "expense-tracker-freelancers",
    internal: "expense-tracker-freelancers",
    en: "expense-tracker-freelancers",
    de: "ausgaben-tracker-freelancer",
  },
  {
    key: "expensify-alternative",
    internal: "expensify-alternative",
    en: "expensify-alternative",
    de: "alternative-zu-expensify",
  },
  {
    key: "lexoffice-alternative",
    internal: "lexoffice-alternative",
    en: "lexoffice-alternative",
    de: "alternative-zu-lexoffice",
  },
  {
    key: "blog/how-receipt-ocr-works",
    internal: "blog/how-receipt-ocr-works",
    en: "blog/how-receipt-ocr-works",
    de: "blog/so-funktioniert-beleg-ocr",
  },
  {
    key: "blog/receipt-scanning-vs-manual-bookkeeping",
    internal: "blog/receipt-scanning-vs-manual-bookkeeping",
    en: "blog/receipt-scanning-vs-manual-bookkeeping",
    de: "blog/kassenbon-scannen-statt-abtippen",
  },
  {
    key: "blog/receipt-to-excel-guide",
    internal: "blog/receipt-to-excel-guide",
    en: "blog/receipt-to-excel-guide",
    de: "blog/kassenbon-in-excel-umwandeln",
  },
  {
    key: "blog/organize-digital-receipts",
    internal: "blog/organize-digital-receipts",
    en: "blog/organize-digital-receipts",
    de: "blog/belege-digitalisieren",
  },
  {
    key: "blog/simple-expense-tracking",
    internal: "blog/simple-expense-tracking",
    en: "blog/simple-expense-tracking",
    de: "blog/einfache-ausgabenverfolgung",
  },
] as const;

function normalizeSlug(slug: string): string {
  return slug.replace(/^\/+|\/+$/g, "");
}

export function findSeoRouteBySlug(slug: string): SeoRoute | null {
  const normalized = normalizeSlug(slug);
  if (!normalized) return null;
  return SEO_ROUTES.find((route) => route.en === normalized || route.de === normalized) ?? null;
}

export function getSeoRoute(key: SeoSlugKey): SeoRoute {
  const route = SEO_ROUTES.find((item) => item.key === key);
  if (!route) throw new Error(`Unknown SEO route: ${key}`);
  return route;
}

/** Locale-correct public path, e.g. `/de/blog/einfache-ausgabenverfolgung`. */
export function publicPath(locale: Locale, key: SeoSlugKey): string {
  const route = getSeoRoute(key);
  return `/${locale}/${route[locale]}`;
}

export function publicUrl(locale: Locale, key: SeoSlugKey): string {
  return `${siteUrl}${publicPath(locale, key)}`;
}

export function seoLanguageAlternates(key: SeoSlugKey): Record<string, string> {
  return {
    de: publicUrl("de", key),
    en: publicUrl("en", key),
    "x-default": publicUrl("en", key),
  };
}

/**
 * Swap `/de/…` ↔ `/en/…` and map the slug to the target locale.
 * Unknown paths only swap the locale prefix.
 */
export function localizePathname(pathname: string, targetLocale: Locale): string {
  const match = pathname.match(/^\/(de|en)(\/.*)?$/);
  if (!match) return `/${targetLocale}`;

  const rest = normalizeSlug(match[2] ?? "");
  if (!rest) return `/${targetLocale}`;

  const route = findSeoRouteBySlug(rest);
  if (route) return `/${targetLocale}/${route[targetLocale]}`;
  return `/${targetLocale}/${rest}`;
}

export type SeoLocaleDecision =
  | { kind: "none" }
  | { kind: "redirect"; pathname: string }
  | { kind: "rewrite"; pathname: string };

/**
 * For a request path like `/de/blog/einfache-ausgabenverfolgung`:
 * - 301 if the slug belongs to the other language
 * - rewrite onto the internal App Router folder when the public DE slug differs
 */
export function decideSeoLocalePath(pathname: string): SeoLocaleDecision {
  const match = pathname.match(/^\/(de|en)(\/.*)?$/);
  if (!match) return { kind: "none" };

  const locale = match[1] as Locale;
  const rest = normalizeSlug(match[2] ?? "");
  if (!rest) return { kind: "none" };

  const route = findSeoRouteBySlug(rest);
  if (!route) return { kind: "none" };

  const publicSlug = route[locale];
  if (rest !== publicSlug) {
    return { kind: "redirect", pathname: `/${locale}/${publicSlug}` };
  }

  if (publicSlug !== route.internal) {
    return { kind: "rewrite", pathname: `/${locale}/${route.internal}` };
  }

  return { kind: "none" };
}
