/**
 * Every route has a name, and the auth group is kept out of search results.
 *
 * Structural rather than behavioural: it reads `src/app` off disk. Metadata is
 * resolved by the framework at render time, so there is nothing to call — but
 * the thing that went wrong here is not subtle and is exactly what a file scan
 * catches. Eight routes had no page-specific title because three of them were
 * Client Components (which cannot export `metadata` at all) and the other five
 * had simply never been given one, so every auth screen's tab, history entry
 * and bookmark read the root layout's default string.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";

const APP = join(import.meta.dirname, "..", "src", "app");

function walk(dir: string): string[] {
  return readdirSync(dir).flatMap((entry) => {
    const full = join(dir, entry);
    return statSync(full).isDirectory() ? walk(full) : [full];
  });
}

const files = walk(APP);
const pages = files.filter((f) => f.endsWith("page.tsx"));
const rel = (f: string) => f.slice(APP.length + 1);

/**
 * Source with comments removed.
 *
 * Needed because the auth pages *document* the inherited `robots` directive in
 * prose, and a test that greps the raw file cannot tell a mention from a
 * declaration — the first version of the test below failed on its own
 * explanatory comments.
 */
const code = (source: string) =>
  source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");

const declaresMetadata = (source: string) =>
  /export\s+const\s+metadata\b/.test(source) ||
  /export\s+(async\s+)?function\s+generateMetadata\b/.test(source);

describe("route metadata", () => {
  test("there are routes to check", () => {
    assert.ok(pages.length > 50, `only found ${pages.length} pages`);
  });

  test("every page declares a title of its own", () => {
    const without = pages
      .filter((f) => !declaresMetadata(code(readFileSync(f, "utf8"))))
      .map(rel);
    assert.deepEqual(
      without,
      [],
      "a page with no metadata inherits the root layout's default title, which is the same string on every route"
    );
  });

  test("a page that declares metadata is not a Client Component", () => {
    /* The two are mutually exclusive — Next silently ignores a `metadata`
       export from a `"use client"` module, so this would fail quietly. */
    const broken = pages
      .filter((f) => {
        const source = code(readFileSync(f, "utf8"));
        return declaresMetadata(source) && /^\s*["']use client["']/m.test(source);
      })
      .map(rel);
    assert.deepEqual(broken, []);
  });
});

describe("auth group", () => {
  const authLayout = files.find((f) => f.endsWith(join("(auth)", "layout.tsx")));

  test("the layout exists and sets robots: noindex once for the whole group", () => {
    assert.ok(authLayout, "(auth)/layout.tsx not found");
    assert.match(
      code(readFileSync(authLayout as string, "utf8")),
      /robots:\s*\{\s*index:\s*false/
    );
  });

  test("no auth page repeats the robots directive", () => {
    /* It is inherited. A per-page copy is the kind of duplication that drifts:
       one page gets indexed because someone edited seven files and not the
       eighth. */
    const repeats = pages
      .filter(
        (f) => f.includes("(auth)") && /robots:/.test(code(readFileSync(f, "utf8")))
      )
      .map(rel);
    assert.deepEqual(repeats, []);
  });
});
