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

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

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

  it("creates app directory with scaffolded boilerplate", () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "init-app-test-"));
    const { exitCode } = runAppInit("my-app", tmpDir, "user-management");
    expect(exitCode).toBe(0);

    const appDir = path.join(tmpDir, "my-app");
    expect(fs.existsSync(appDir)).toBe(true);
    expect(fs.existsSync(path.join(appDir, "backend"))).toBe(true);
    expect(fs.existsSync(path.join(appDir, "frontend"))).toBe(true);
    expect(fs.existsSync(path.join(appDir, "docs"))).toBe(true);
    expect(fs.existsSync(path.join(appDir, "README.md"))).toBe(true);

    const indexHtml = fs.readFileSync(path.join(appDir, "frontend", "index.html"), "utf-8");
    expect(indexHtml).toContain("<title>my-app</title>");
    const appTsx = fs.readFileSync(path.join(appDir, "frontend", "src", "App.tsx"), "utf-8");
    expect(appTsx).toContain('title="my-app"');
  });

  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 } = runAppInit("my-app", tmpDir, "user-management");
    expect(exitCode).toBe(0);
  });
});
