/**
 * `mcpctl rotate secretbackend <name>` — force an immediate token rotation on
 * a wizard-provisioned OpenBao backend.
 *
 * Hits `POST /api/v1/secretbackends/:id/rotate` after resolving name → id.
 * Gated server-side by the `rotate-secretbackend` operation.
 */
import { Command } from 'commander';
import type { ApiClient } from '../api-client.js';
import { resolveNameOrId } from './shared.js';

export interface RotateCommandDeps {
  client: ApiClient;
  log: (...args: unknown[]) => void;
}

export function createRotateCommand(deps: RotateCommandDeps): Command {
  const { client, log } = deps;

  const cmd = new Command('rotate')
    .description('Force rotation of a credential-rotating resource (currently: secretbackend)');

  cmd.command('secretbackend')
    .alias('sb')
    .description('Rotate the vault token on an OpenBao SecretBackend (wizard-provisioned)')
    .argument('<name>', 'SecretBackend name or id')
    .action(async (nameOrId: string) => {
      const id = await resolveNameOrId(client, 'secretbackends', nameOrId);
      const res = await client.post<{ ok?: boolean; tokenMeta?: Record<string, unknown>; error?: string }>(
        `/api/v1/secretbackends/${id}/rotate`,
        {},
      );
      if (res.ok !== true) {
        throw new Error(`rotation failed: ${res.error ?? 'unknown error'}`);
      }
      log(`secretbackend '${nameOrId}' rotated.`);
      const meta = res.tokenMeta ?? {};
      if (typeof meta.generatedAt === 'string') {
        log(`  generated:    ${meta.generatedAt}`);
      }
      if (typeof meta.nextRenewalAt === 'string') {
        log(`  next renewal: ${meta.nextRenewalAt}`);
      }
      if (typeof meta.validUntil === 'string') {
        log(`  valid until:  ${meta.validUntil}`);
      }
    });

  return cmd;
}
