import { errorCodeToClassName, type ParsedCommandDoc } from "./parse-command-doc";

export function moduleNameToPrefix(moduleName: string): string {
  return moduleName.toUpperCase().replace(/-/g, "_");
}

export function generateErrors(moduleName: string, docs: ParsedCommandDoc[]): string {
  const seen = new Set<string>();
  const lines: string[] = [];
  const prefix = moduleNameToPrefix(moduleName);

  for (const doc of docs) {
    for (const error of doc.errors) {
      if (seen.has(error.code)) continue;
      seen.add(error.code);

      const className = errorCodeToClassName(error.code);
      const prefixedCode = `${prefix}_${error.code}`;
      lines.push(`export const ${className} = createDomainError(`);
      lines.push(`  "${className}", "${prefixedCode}",`);
      const escapedDesc = error.description.replace(/`/g, "'");
      lines.push(`  (identifier: string) => \`${escapedDesc}: \${identifier}\`,`);
      lines.push(`);`);
      lines.push(``);
    }
  }

  if (lines.length === 0) return "";

  return `// @generated — do not edit
import { createDomainError } from "@tailor-platform/erp-kit/module";

${lines.join("\n")}`;
}
