/**
 * OpenBao / Vault policy template for mcpd's wizard-provisioned backend.
 *
 * The policy is deliberately narrow:
 *   - Read/write/list/delete under `<mount>/{data,metadata}/<pathPrefix>/*`
 *   - Self-rotation: mcpd can mint its successor via the dedicated token role
 *     and revoke its predecessor by accessor.
 *
 * Keeping the paths in one place lets the wizard and the rotator agree on
 * exactly which capabilities the stored token has, and lets tests assert the
 * generated HCL is stable.
 */

export interface AppMcpdPolicyConfig {
  /** KV v2 mount name. Default: 'secret'. */
  mount: string;
  /** Path prefix under the mount (the directory mcpd is confined to). Default: 'mcpd'. */
  pathPrefix: string;
  /** Token role name the policy allows self-rotation against. Default: 'app-mcpd-role'. */
  tokenRole: string;
}

export function buildAppMcpdPolicyHcl(cfg: AppMcpdPolicyConfig): string {
  const { mount, pathPrefix, tokenRole } = cfg;
  const prefix = pathPrefix.replace(/^\/|\/$/g, '');
  return [
    `path "${mount}/data/${prefix}/*"      { capabilities = ["create", "read", "update"] }`,
    `path "${mount}/metadata/${prefix}/*"  { capabilities = ["list", "delete"] }`,
    `path "${mount}/metadata/${prefix}/"   { capabilities = ["list"] }`,
    `path "auth/token/create/${tokenRole}" { capabilities = ["create", "update"] }`,
    `path "auth/token/revoke-accessor"     { capabilities = ["update"] }`,
    `path "auth/token/lookup-self"         { capabilities = ["read"] }`,
    '',
  ].join('\n');
}
