import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { runInit } from "./init";

describe("runInit", () => {
  let tmpDir: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-test-"));
  });

  afterEach(() => {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it("copies skills, workflows, symlink, and scaffolds project on fresh repo", () => {
    const result = runInit("test-project", tmpDir);
    expect(result.exitCode).toBe(0);

    // Skills
    const skillPath = path.join(
      tmpDir,
      ".agents",
      "skills",
      "erp-kit-module-1-requirements",
      "SKILL.md",
    );
    expect(fs.existsSync(skillPath)).toBe(true);

    // Symlink
    const claudeSkills = path.join(tmpDir, ".claude", "skills");
    expect(fs.lstatSync(claudeSkills).isSymbolicLink()).toBe(true);

    // Workflows
    const wfPath = path.join(tmpDir, ".github", "workflows", "erp-kit-check.yml");
    expect(fs.existsSync(wfPath)).toBe(true);

    // Scaffold: package.json
    const pkgPath = path.join(tmpDir, "package.json");
    expect(fs.existsSync(pkgPath)).toBe(true);
    const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")) as { name: string; private: boolean };
    expect(pkg.name).toBe("test-project");
    expect(pkg.private).toBe(true);

    // Scaffold: pnpm-workspace.yaml
    expect(fs.existsSync(path.join(tmpDir, "pnpm-workspace.yaml"))).toBe(true);

    // Scaffold: .gitignore
    expect(fs.existsSync(path.join(tmpDir, ".gitignore"))).toBe(true);

    // Scaffold: license.config.json
    expect(fs.existsSync(path.join(tmpDir, "license.config.json"))).toBe(true);

    // Scaffold: apps/ and modules/
    expect(fs.existsSync(path.join(tmpDir, "apps", ".gitkeep"))).toBe(true);
    expect(fs.existsSync(path.join(tmpDir, "modules", ".gitkeep"))).toBe(true);
  });

  it("refuses to run if already initialized", () => {
    runInit("test-project", tmpDir);
    const result = runInit("test-project", tmpDir);
    expect(result.exitCode).toBe(1);
  });

  it("preserves non-erp-kit skills", () => {
    const customDir = path.join(tmpDir, ".agents", "skills", "my-custom-skill");
    fs.mkdirSync(customDir, { recursive: true });
    fs.writeFileSync(path.join(customDir, "SKILL.md"), "# Custom");
    runInit("test-project", tmpDir);
    expect(fs.readFileSync(path.join(customDir, "SKILL.md"), "utf-8")).toBe("# Custom");
  });
});
