import fs from "node:fs";
import path from "node:path";
import { PACKAGE_ROOT, readErpKitVersion } from "../../../util";
import { type CommandResult, silentFailure } from "../../lib/command-result";
import { copyTemplateDir } from "../../lib/copy-template-dir";
import { runGenerateDoc } from "../../lib/generate-doc";
import { MODULE_SCHEMAS } from "../schemas";

export function scaffoldModuleBoilerplate(moduleDir: string, moduleName: string): void {
  const templateDir = path.join(PACKAGE_ROOT, "templates", "scaffold", "module");
  const erpKitVersion = readErpKitVersion();
  const replacements = {
    "template-module": moduleName,
    '"workspace:*"': `"${erpKitVersion}"`,
  };
  const placeholderFiles = new Set(["package.json", "tailor.config.ts"]);
  copyTemplateDir(templateDir, moduleDir, replacements, placeholderFiles);
}

export function scaffoldModule(name: string, dir: string): number {
  const moduleDir = path.resolve(dir, name);
  fs.mkdirSync(moduleDir, { recursive: true });
  scaffoldModuleBoilerplate(moduleDir, name);
  return 0;
}

export async function runModuleInit(
  name: string,
  dir: string,
  cwd: string,
): Promise<CommandResult> {
  const initResult = scaffoldModule(name, dir);
  if (initResult !== 0) return silentFailure(initResult);

  return runGenerateDoc(path.join(dir, name, "README.md"), MODULE_SCHEMAS.module, cwd);
}
