import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { loadFragmentsConfig, normalizePresetNames, resolveGovernancePolicy } from "./policy.js";

describe("TypeStyle policy resolver", () => {
  it("loads fragments.config.* upward and expands preset-only governance", async () => {
    const root = await mkdtemp(join(tmpdir(), "fragments-policy-"));
    const child = join(root, "src", "components");
    await mkdir(child, { recursive: true });
    await writeFile(
      join(root, "fragments.config.ts"),
      [
        "export default {",
        "  components: ['src/**/*.tsx'],",
        "  govern: { presets: ['fragments/recommended'] },",
        "};",
      ].join("\n")
    );

    const loaded = await loadFragmentsConfig({ rootDir: child });
    const resolved = resolveGovernancePolicy(loaded.config?.govern);

    expect(loaded.configPath).toBe(join(root, "fragments.config.ts"));
    expect(loaded.configDir).toBe(root);
    expect(loaded.config?.components).toEqual(["src/**/*.tsx"]);
    expect(resolved.source).toBe("config");
    expect(resolved.presetsLoaded).toEqual(["fragments"]);
    expect(
      resolved.policy?.styles?.some((rule) => rule.kind === "style.cssVars.mustBeDefined")
    ).toBe(true);
  });

  it("normalizes preset aliases once", () => {
    expect(
      normalizePresetNames([
        "fragments/recommended",
        "fragments",
        "universal@2",
        "tailwind/recommended",
        "tailwind@2",
        "unknown",
      ])
    ).toEqual(["fragments", "universal", "tailwind"]);
  });
});
