declare const process: { cwd(): string };
declare function require(name: string): {
  readFileSync?: (path: string, encoding: string) => string;
  join?: (...parts: string[]) => string;
};

const { readFileSync } = require("node:fs");
const { join } = require("node:path");

if (!readFileSync || !join) {
  throw new Error("测试运行环境缺少文件读取能力");
}

const routerPath = join(process.cwd(), "src/router/index.ts");
const routerSource = readFileSync(routerPath, "utf-8");

assertIncludes(routerSource, "await auth.loadSession();");
assertIncludes(routerSource, "catch");
assertIncludes(routerSource, "auth.logout();");
assertIncludes(routerSource, 'return { path: "/login", query: { redirect: to.fullPath } };');
assertBefore(routerSource, "try", "await auth.loadSession();");
assertBefore(routerSource, "await auth.loadSession();", "auth.logout();");

function assertIncludes(content: string, expected: string): void {
  if (!content.includes(expected)) {
    throw new Error(`期望包含 ${expected}`);
  }
}

function assertBefore(content: string, first: string, second: string): void {
  const firstIndex = content.indexOf(first);
  const secondIndex = content.indexOf(second);
  if (firstIndex === -1 || secondIndex === -1 || firstIndex >= secondIndex) {
    throw new Error(`期望 ${first} 出现在 ${second} 之前`);
  }
}
