import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, it, expect, afterEach } from "vitest";
import { runInitModule, runInitApp } from "./init-module";

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

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

  it("creates module directory", () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-module-test-"));
    const exitCode = runInitModule("my-module", tmpDir);
    expect(exitCode).toBe(0);
    expect(fs.existsSync(path.join(tmpDir, "my-module"))).toBe(true);
  });

  it("succeeds if module directory already exists", () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-module-test-"));
    const moduleDir = path.join(tmpDir, "my-module");
    fs.mkdirSync(moduleDir, { recursive: true });

    const exitCode = runInitModule("my-module", tmpDir);
    expect(exitCode).toBe(0);
  });
});

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

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

  it("creates app directory", () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-app-test-"));
    const exitCode = runInitApp("my-app", tmpDir);
    expect(exitCode).toBe(0);
    expect(fs.existsSync(path.join(tmpDir, "my-app"))).toBe(true);
  });

  it("succeeds if app directory already exists", () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-app-test-"));
    const appDir = path.join(tmpDir, "my-app");
    fs.mkdirSync(appDir, { recursive: true });

    const exitCode = runInitApp("my-app", tmpDir);
    expect(exitCode).toBe(0);
  });
});
