/**
 * POST /api/v1/secretbackends/:id/rotate — force an immediate rotation.
 *
 * Used by the wizard (final verify step) + operators troubleshooting a
 * stale backend. RBAC handled in the global hook via the operation
 * `rotate-secretbackend` (see `main.ts:mapUrlToPermission`).
 */
import type { FastifyInstance } from 'fastify';
import type { SecretBackendRotator } from '../services/secret-backend-rotator.service.js';
import { NotFoundError } from '../services/mcp-server.service.js';

export function registerSecretBackendRotateRoutes(
  app: FastifyInstance,
  rotator: SecretBackendRotator,
): void {
  app.post<{ Params: { id: string } }>('/api/v1/secretbackends/:id/rotate', async (request, reply) => {
    try {
      const tokenMeta = await rotator.rotateOne(request.params.id);
      return { ok: true, tokenMeta };
    } catch (err) {
      if (err instanceof NotFoundError) {
        reply.code(404);
        return { error: err.message };
      }
      reply.code(502);
      return { error: err instanceof Error ? err.message : String(err) };
    }
  });
}
