import enMessages from "../../../messages/en.json";
import frMessages from "../../../messages/fr.json";
import { routing } from "@/i18n/routing";
import { BLOG_CATEGORIES } from "./categories";

type LocalizedPathname = string | { en: string; fr: string };

/**
 * Build-time guards for the blog category config. Imported by the data layer
 * (`src/lib/blog/index.ts`), so this runs during `bun run build`.
 *
 * 1. No category slug may collide with an existing localized route pathname
 *    (a static page always wins over the dynamic `[category]` segment).
 * 2. Every category id must have a `BlogPage.categories.<id>` label key in
 *    BOTH en and fr message files (no dead/missing label keys).
 */

const LOCALES = ["en", "fr"] as const;

/** Collect localized route pathname values per locale, leading slash stripped. */
function routePathsByLocale(): Record<"en" | "fr", Set<string>> {
  const out: Record<"en" | "fr", Set<string>> = { en: new Set(), fr: new Set() };
  for (const value of Object.values(routing.pathnames) as LocalizedPathname[]) {
    for (const locale of LOCALES) {
      const raw = typeof value === "string" ? value : value[locale];
      // Skip dynamic templates (e.g. "/[category]") — only real static paths collide.
      if (raw.includes("[")) continue;
      out[locale].add(raw.replace(/^\//, ""));
    }
  }
  return out;
}

const routePaths = routePathsByLocale();

for (const category of BLOG_CATEGORIES) {
  for (const locale of LOCALES) {
    const slug = category.slug[locale];
    if (routePaths[locale].has(slug)) {
      throw new Error(`[blog] category slug '${slug}' collides with route '/${slug}'`);
    }
  }
}

const enLabels = (enMessages.BlogPage?.categories ?? {}) as Record<string, string>;
const frLabels = (frMessages.BlogPage?.categories ?? {}) as Record<string, string>;

for (const category of BLOG_CATEGORIES) {
  if (!enLabels[category.id]) {
    throw new Error(
      `[blog] category '${category.id}' missing BlogPage.categories.${category.id} label in en.json`,
    );
  }
  if (!frLabels[category.id]) {
    throw new Error(
      `[blog] category '${category.id}' missing BlogPage.categories.${category.id} label in fr.json`,
    );
  }
}
