export function generatePermissions(
  moduleName: string,
  commands: { name: string; permissionScope: string }[],
): string {
  // Group commands by permissionScope
  const scopeMap = new Map<string, string[]>();
  for (const cmd of commands) {
    if (!cmd.permissionScope) {
      throw new Error(
        `Command "${cmd.name}" in module "${moduleName}" is missing a Permission Scope section`,
      );
    }
    const list = scopeMap.get(cmd.permissionScope) ?? [];
    list.push(cmd.name);
    scopeMap.set(cmd.permissionScope, list);
  }

  // Sort scopes and commands within each scope
  const scopeEntries = [...scopeMap.entries()]
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([scope, cmds]) => {
      const cmdEntries = cmds
        .sort()
        .map((name) => `    "${name}",`)
        .join("\n");
      return `  ${scope}: [\n${cmdEntries}\n  ],`;
    })
    .join("\n");

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

export const { permissions } = definePermissions("${moduleName}", {
${scopeEntries}
} as const);
`;
}
