import { siteUrl } from "@/lib/env";
import { defaultLocale, locales, type Locale } from "@/lib/i18n";

/**
 * Canonical + `hreflang` alternates for a page. `canonical` points at the
 * requested locale when that locale is available, otherwise the default locale
 * (or the first available one); `languages` lists only the `available` locales
 * plus `x-default`. Mirrors the sitemap so on-page signals and the sitemap
 * agree.
 *
 * `available` defaults to every locale (preserving existing 2-arg callers).
 * Pass a narrower list for routes that only exist in some locales. For
 * content-driven blog posts, use the resolver in `lib/blog/posts.ts` instead.
 */
export function localizedAlternates(
  path: string,
  lang: string,
  available: readonly Locale[] = locales,
): { canonical: string; languages: Record<string, string> } {
  // Normalize so the emitted canonical matches the URL Next.js actually serves.
  // The project leaves `trailingSlash` at its default (false) in next.config.ts,
  // so served URLs never end in `/`. Strip any leading-slash duplication from
  // `path` and any trailing slash from the result to stay deterministic
  // regardless of how callers pass `path` (`""`, `"/pricing"`, `"/pricing/"`).
  const url = (l: string) => {
    const suffix = path ? `/${path.replace(/^\/+/, "").replace(/\/+$/, "")}` : "";
    return `${siteUrl}/${l}${suffix}`;
  };

  const languages: Record<string, string> = {};
  for (const l of available) languages[l] = url(l);
  const xDefault = available.includes(defaultLocale)
    ? defaultLocale
    : available[0];
  languages["x-default"] = url(xDefault);

  const isAvailable = (available as readonly string[]).includes(lang);
  const canonicalLocale = isAvailable ? lang : xDefault;
  return { canonical: url(canonicalLocale), languages };
}
