import { expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { inspectProject, repairProject } from "../src/doctor.ts";

test("doctor reports a healthy minimal project", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-doctor-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  writeFileSync(join(root, "package.json"), JSON.stringify({ name: "app" }));
  writeFileSync(join(root, "wrnexus.config.ts"), "export default {};");
  const checks = inspectProject(root);
  expect(checks.every((check) => check.ok)).toBe(true);
});

test("doctor returns actionable missing-project checks", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-doctor-"));
  const checks = inspectProject(root);
  expect(checks.find((check) => check.name === "package.json")?.ok).toBe(false);
  expect(checks.find((check) => check.name === "app/pages")?.detail).toBe("Create app/pages");
});

test("doctor --fix applies safe repairs and is idempotent", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-doctor-fix-"));
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "app",
      dependencies: { "@wrnexus/core": "^0.8.0", "@wrnexus/router": "^0.7.0" },
      wrnexus: { version: "0.7.0" },
    }),
  );
  mkdirSync(join(root, "app", "components"), { recursive: true });
  writeFileSync(
    join(root, "app", "components", "Greeting.wrn"),
    'component Greeting { props { name:string="World" } view { <p>{name}</p> } }',
  );

  const repairs = repairProject(root);
  expect(repairs.map(({ name }) => name)).toContain("app/pages");
  expect(repairs.map(({ name }) => name)).toContain("configuration");
  expect(existsSync(join(root, "wrnexus.config.ts"))).toBe(true);
  const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
  expect(manifest.dependencies["@wrnexus/router"]).toBe("^0.7.0");
  expect(manifest.wrnexus.version).toBe("0.8.0");
  expect(repairProject(root)).toEqual([]);
});
