import { test, describe } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { discoverStrykerConfigs } from "./mutate.mjs";

describe("discoverStrykerConfigs", () => {
  test("finds stryker.config.json under packages/* and apps/*", () => {
    const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mutate-disc-"));
    try {
      fs.mkdirSync(path.join(tmpRoot, "packages", "p1"), { recursive: true });
      fs.mkdirSync(path.join(tmpRoot, "apps", "a1"), { recursive: true });
      fs.mkdirSync(path.join(tmpRoot, "packages", "no-stryker"), {
        recursive: true,
      });
      fs.writeFileSync(
        path.join(tmpRoot, "packages", "p1", "stryker.config.json"),
        "{}",
      );
      fs.writeFileSync(
        path.join(tmpRoot, "packages", "p1", "package.json"),
        JSON.stringify({ name: "@repo/p1" }),
      );
      fs.writeFileSync(
        path.join(tmpRoot, "apps", "a1", "stryker.config.json"),
        "{}",
      );
      fs.writeFileSync(
        path.join(tmpRoot, "apps", "a1", "package.json"),
        JSON.stringify({ name: "@repo/a1" }),
      );

      const found = discoverStrykerConfigs(tmpRoot);
      assert.equal(found.length, 2);
      const names = found.map((f) => f.packageName).sort();
      assert.deepEqual(names, ["@repo/a1", "@repo/p1"]);
    } finally {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    }
  });

  test("falls back to packageDir when no package.json", () => {
    const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mutate-disc2-"));
    try {
      fs.mkdirSync(path.join(tmpRoot, "packages", "no-pkg-json"), {
        recursive: true,
      });
      fs.writeFileSync(
        path.join(tmpRoot, "packages", "no-pkg-json", "stryker.config.json"),
        "{}",
      );

      const found = discoverStrykerConfigs(tmpRoot);
      assert.equal(found.length, 1);
      assert.equal(found[0].packageName, "packages/no-pkg-json");
    } finally {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    }
  });

  test("returns empty when nothing matches", () => {
    const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mutate-disc3-"));
    try {
      const found = discoverStrykerConfigs(tmpRoot);
      assert.deepEqual(found, []);
    } finally {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    }
  });
});
