import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import fs from "node:fs";
import path from "node:path";
import { describe, it, expect } from "vitest";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLI_PATH = path.resolve(__dirname, "..", "dist", "cli.mjs");
const REPO_ROOT = path.resolve(__dirname, "..", "..", "..");

const skipReason = fs.existsSync(CLI_PATH) ? undefined : "Run `pnpm build` first";

describe.skipIf(skipReason)("integration", () => {
  it("module check command runs against erp-kit modules", () => {
    try {
      const result = execFileSync(
        "node",
        [CLI_PATH, "module", "check", "--path", "packages/erp-kit/src/modules"],
        {
          cwd: REPO_ROOT,
          encoding: "utf-8",
          env: { ...process.env },
        },
      );
      expect(result).toBeDefined();
    } catch (err: unknown) {
      const error = err as { status: number; stderr: string };
      // exit code 1 = validation errors in docs (acceptable)
      // exit code 2 = CLI usage error (unexpected)
      expect(error.status).toBe(1);
    }
  });

  it("module sync-check command runs against erp-kit modules", () => {
    try {
      const result = execFileSync(
        "node",
        [CLI_PATH, "module", "sync-check", "--path", "packages/erp-kit/src/modules"],
        {
          cwd: REPO_ROOT,
          encoding: "utf-8",
          env: { ...process.env },
        },
      );
      expect(result).toContain("docs-sync-check");
    } catch (err: unknown) {
      const error = err as { status: number; stdout: string };
      // sync-check may fail with errors=1 but should still produce a report
      expect(error.stdout).toContain("docs-sync-check");
    }
  });

  it("--help prints usage", () => {
    const result = execFileSync("node", [CLI_PATH, "--help"], {
      encoding: "utf-8",
    });
    expect(result).toContain("erp-kit");
    expect(result).toContain("module");
    expect(result).toContain("app");
  });
});
