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 "./usecase-must-have-test-file.js";

function makeUseCaseFixture({ withTest }) {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "umht-"));
  const useCase = path.join(dir, "sign-in.use-case.ts");
  fs.writeFileSync(useCase, `export const signInUseCase = () => async () => {};`);
  if (withTest) {
    fs.writeFileSync(path.join(dir, "sign-in.use-case.test.ts"), `import { it } from "vitest"; it("works", () => {});`);
  }
  return { useCase };
}

const tester = new RuleTester({ languageOptions: { ecmaVersion: "latest", sourceType: "module" } });

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

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