import fs from "node:fs";
import path from "node:path";
import { PACKAGE_ROOT, readErpKitVersion } from "../../../util";
import { type CommandResult, success } from "../../lib/command-result";
import { copyTemplateDir } from "../../lib/copy-template-dir";

export function listAppTemplates(): string[] {
  const appTemplateRoot = path.join(PACKAGE_ROOT, "templates", "scaffold", "app");
  return fs
    .readdirSync(appTemplateRoot, { withFileTypes: true })
    .filter((e) => e.isDirectory())
    .map((e) => e.name);
}

export function scaffoldAppBoilerplate(
  appDir: string,
  appName: string,
  templateName: string,
): void {
  const templateDir = path.join(PACKAGE_ROOT, "templates", "scaffold", "app", templateName);
  const erpKitVersion = readErpKitVersion();
  const replacements = {
    "template-app-frontend": `${appName}-frontend`,
    "template-app-backend": appName,
    "template-app": appName,
    '"workspace:*"': `"${erpKitVersion}"`,
  };
  const placeholderFiles = new Set([
    "package.json",
    "tailor.config.ts",
    "index.html",
    "setup.ts",
    "App.tsx",
  ]);
  copyTemplateDir(templateDir, appDir, replacements, placeholderFiles);
}

export function runAppInit(name: string, dir: string, templateName: string): CommandResult {
  const appDir = path.resolve(dir, name);
  fs.mkdirSync(appDir, { recursive: true });
  scaffoldAppBoilerplate(appDir, name, templateName);
  return success();
}
