import { describe, it } from "vitest";
import { RuleTester } from "eslint";
import path from "node:path";
import os from "node:os";
import fs from "node:fs";
import rule from "./component-must-have-test.js";

function makeFixture({ withTest }) {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "cmht-"));
  const dir = path.join(root, "packages", "core-ui", "src", "atoms", "Button");
  fs.mkdirSync(dir, { recursive: true });
  const component = path.join(dir, "Button.tsx");
  fs.writeFileSync(component, `export const Button = () => <button>x</button>;`);
  if (withTest) {
    fs.writeFileSync(path.join(dir, "Button.test.tsx"), `import { it } from "vitest"; it("works", () => {});`);
  }
  return { component };
}

const tester = new RuleTester({
  languageOptions: {
    parser: await import("@typescript-eslint/parser"),
    ecmaVersion: "latest",
    sourceType: "module",
    parserOptions: { ecmaFeatures: { jsx: true } },
  },
});

describe("component-must-have-test", () => {
  it("passes when sibling .test.tsx exists", () => {
    const { component } = makeFixture({ withTest: true });
    tester.run("component-must-have-test", rule, {
      valid: [{ filename: component, code: fs.readFileSync(component, "utf8") }],
      invalid: [],
    });
  });

  it("fires when no sibling .test.tsx exists", () => {
    const { component } = makeFixture({ withTest: false });
    tester.run("component-must-have-test", rule, {
      valid: [],
      invalid: [{
        filename: component,
        code: fs.readFileSync(component, "utf8"),
        errors: [{ messageId: "missingTest" }],
      }],
    });
  });
});
