import { describe, it, expect } from "vitest";
import path from "node:path";
import os from "node:os";
import fs from "node:fs";
import { readManifestSource, manifestPathForFeature, featureRootForFile } from "./_manifest-source.js";

function writeTempFile(filename, contents) {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "manifest-source-"));
  const filepath = path.join(dir, filename);
  fs.writeFileSync(filepath, contents);
  return { dir, filepath };
}

describe("_manifest-source", () => {
  describe("readManifestSource", () => {
    it("returns { name, requiredCores: [] } for a minimal manifest", () => {
      const { filepath } = writeTempFile(
        "feature.manifest.ts",
        `import { defineFeature } from "@repo/core-shared/conformance";
export const xManifest = defineFeature({
  name: "test",
  requiredCores: [],
  useCases: {},
  realtimeChannels: [],
  jobs: [],
} as const);`
      );
      expect(readManifestSource(filepath)).toEqual({ name: "test", requiredCores: [] });
    });

    it("extracts multi-element requiredCores", () => {
      const { filepath } = writeTempFile(
        "feature.manifest.ts",
        `export const xManifest = defineFeature({
  name: "auth",
  requiredCores: ["audit", "events"],
  useCases: {},
  realtimeChannels: [],
  jobs: [],
} as const);`
      );
      expect(readManifestSource(filepath)).toEqual({ name: "auth", requiredCores: ["audit", "events"] });
    });

    it("returns null when the file does not exist", () => {
      expect(readManifestSource("/nonexistent/path/feature.manifest.ts")).toBeNull();
    });

    it("returns null when the file is unreadable as a manifest (no name field)", () => {
      const { filepath } = writeTempFile("feature.manifest.ts", `export const x = 1;`);
      expect(readManifestSource(filepath)).toBeNull();
    });
  });

  describe("manifestPathForFeature", () => {
    it("returns the canonical manifest path for a feature root", () => {
      expect(manifestPathForFeature("/repo/packages/auth")).toBe(
        path.join("/repo/packages/auth", "src", "feature.manifest.ts"),
      );
    });
  });

  describe("featureRootForFile", () => {
    it("returns the package root containing a use-case file", () => {
      const file = "/repo/packages/auth/src/application/use-cases/sign-in.use-case.ts";
      expect(featureRootForFile(file, "/repo")).toBe("/repo/packages/auth");
    });

    it("returns null for files outside the packages tree", () => {
      const file = "/repo/apps/web-next/src/app/page.tsx";
      expect(featureRootForFile(file, "/repo")).toBeNull();
    });
  });
});
