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

const formFieldTagPattern = /<(input|select|textarea)\b[\s\S]*?(?:>|\/>)/g;

function sourceFiles(dir: string): string[] {
  if (!existsSync(dir)) return [];
  return readdirSync(dir).flatMap((entry) => {
    const path = join(dir, entry);
    const stat = statSync(path);
    if (stat.isDirectory()) return sourceFiles(path);
    if (!/\.(tsx|jsx)$/.test(entry)) return [];
    if (/\.(test|spec)\./.test(entry)) return [];
    return [path];
  });
}

function lineNumber(source: string, index: number) {
  return source.slice(0, index).split("\n").length;
}

describe("adminfront form field diagnostics", () => {
  it("keeps raw rendered form fields identifiable for browser autofill diagnostics", () => {
    const offenders: string[] = [];

    for (const file of sourceFiles("src")) {
      const source = readFileSync(file, "utf8");
      for (
        let match = formFieldTagPattern.exec(source);
        match !== null;
        match = formFieldTagPattern.exec(source)
      ) {
        const tag = match[0];
        if (/\b(id|name)\s*=/.test(tag)) continue;
        if (/\{\.\.\s*[^}]+\}/.test(tag)) continue;
        offenders.push(`${file}:${lineNumber(source, match.index)}`);
      }
    }

    expect(offenders).toEqual([]);
  });
});
