import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it } from "vitest";
import {
  mergeDiscoveryConfigs,
  normalizeDiscoveryConfig,
  resolveDiscoveryRoots,
  shouldExcludeDiscoveryPath,
} from "./path-policy.mjs";

const cleanups = [];

afterEach(() => {
  while (cleanups.length > 0) {
    cleanups.pop()();
  }
});

describe("discovery path policy", () => {
  it("normalizes roots and excludes as relative paths", () => {
    expect(
      normalizeDiscoveryConfig({
        roots: ["./app/", "src/app"],
        exclude: ["./coverage/", "dist"],
      })
    ).toEqual({
      roots: ["app", "src/app"],
      exclude: ["coverage", "dist"],
    });
  });

  it("merges excludes without losing later roots", () => {
    expect(
      mergeDiscoveryConfigs(
        { roots: ["src"], exclude: ["coverage"] },
        { exclude: ["dist"] },
        { roots: ["app"], exclude: ["test-results"] }
      )
    ).toEqual({
      roots: ["app"],
      exclude: ["coverage", "dist", "test-results"],
    });
  });

  it("treats exclude paths as path prefixes rather than bare directory names", () => {
    expect(shouldExcludeDiscoveryPath("coverage", ["coverage"])).toBe(true);
    expect(shouldExcludeDiscoveryPath("coverage/report/index.html", ["coverage"])).toBe(true);
    expect(shouldExcludeDiscoveryPath("app/coverage", ["coverage"])).toBe(false);
    expect(shouldExcludeDiscoveryPath("src/app/coverage", ["coverage"])).toBe(false);
  });

  it("resolves only existing discovery roots", () => {
    const productDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-discovery-roots-"));
    cleanups.push(() => fs.rmSync(productDir, { recursive: true, force: true }));
    fs.mkdirSync(path.join(productDir, "app"), { recursive: true });
    fs.mkdirSync(path.join(productDir, "src", "app"), { recursive: true });

    const roots = resolveDiscoveryRoots(productDir, ["app", "missing", "src/app"]);
    expect(roots).toEqual([
      path.join(productDir, "app"),
      path.join(productDir, "src", "app"),
    ]);
  });
});
