import { readdirSync, readFileSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { describe, expect, it } from "vitest";

const root = join(import.meta.dirname);
const files = readdirSync(root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts"));

describe("module boundaries", () => {
  it.each(files)("%s", (file) => {
    const text = readFileSync(join(root, file), "utf8");
    const layer = file.match(/\.(routes|service|repository|rules)\.ts$/)?.[1];
    const own = file.split(sep)[0] === "modules" ? file.split(sep)[1] : undefined;
    const limit = layer === "routes" ? 400 : 700;
    expect(text.split("\n").length, `${file} is over ${limit} lines: split it`).toBeLessThanOrEqual(limit);
    for (const [, spec] of text.matchAll(/from "(\.[^"]+)"/g)) {
      const target = relative(root, join(root, file, "..", spec!)).split(sep);
      const other = target[0] === "modules" ? target[1] : undefined;
      if (own && other && other !== own) expect(target[2], `${file}: use only the public index.ts of ${other}`).toBe("index.js");
      if (target[0] === "core" || target[0] === "shared") continue;
      if (file.startsWith("shared")) throw new Error(`${file}: shared code must not import ${spec}`);
      if (file.startsWith("core") && other) throw new Error(`${file}: core must not import modules`);
    }
    if (layer === "routes" || layer === "rules") expect(text, `${file}: no database access in ${layer}`).not.toMatch(/core\/db\//);
  });
});
