/**
 * SSH HTTP layer — admin router (`/api/ssh/admin/*`).
 *
 * Extracted verbatim from src/bridge/ssh-api.ts (split refactor). Shared
 * types / helpers live in ssh-api-shared.ts; the user router lives in
 * ssh-user-api.ts. Mounted from src/bridge/server.ts (via ssh-subsystem)
 * ONLY when `ssh.enabled=true` AND `MCP_ENCRYPTION_KEY` is configured.
 * Every admin write path requires `body.reason` >= 8 chars and is audit
 * logged. See the design conventions in the ssh-api.ts barrel header.
 */

import { Router } from 'express';

import type { SshConnectionRepo } from '../ssh/connection-repo.js';
import type { SshGrant, SshGrantSubjectType } from '../ssh/grants-repo.js';
import { logger } from '../logger.js';
import {
  type SshApiDeps,
  type SshEncryptResult,
  validateReason,
  maintenance503,
  safePort,
  safeString,
  safeOptionalString,
  safePathPrefix,
  safeUuid,
  safeExpiresAt,
  safeSubjectType,
  presentConnection,
  presentGrant,
  safeLimit,
  jsonError,
  makeSshLocalUserMiddleware,
} from './ssh-api-shared.js';
// ──────────────────────────────────────────────────────────────────────
// Admin router — /api/ssh/admin/*
// ──────────────────────────────────────────────────────────────────────

export function createSshAdminRouter(deps: SshApiDeps): Router {
  const router = Router();
  router.use(makeSshLocalUserMiddleware(deps.authActive ?? true));

  // GET /api/ssh/admin/connections
  router.get('/connections', deps.requireAdmin, (_req, res) => {
    try {
      const list = deps.connectionRepo.listAll();
      res.json({ connections: list.map(presentConnection) });
    } catch (e) {
      logger.warn(`[ssh:api] admin list connections failed err=${String(e)}`);
      jsonError(res, 500, 'list_failed');
    }
  });

  router.get('/connections/:id', deps.requireAdmin, (req, res) => {
    try {
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      let publicKey: string | null = null;
      try {
        publicKey = deps.derivePublicKey(conn.ownerId, conn.privateKeyEnc, conn.passphraseEnc, conn.spaceId);
      } catch (e) {
        logger.warn(`[ssh:api] admin derive public key failed id=${conn.id} err=${String(e)}`);
      }
      res.json({ connection: presentConnection(conn), publicKey });
    } catch (e) {
      logger.warn(`[ssh:api] admin get connection failed err=${String(e)}`);
      jsonError(res, 500, 'get_failed');
    }
  });

  router.patch('/connections/:id/disable', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      const ok = deps.connectionRepo.disableByAdmin(conn.id, String(req.body.reason), userId);
      if (!ok) { jsonError(res, 404, 'not_found'); return; }
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.connection.disable',
          entityType: 'ssh_connection',
          entityId: conn.id,
          connectionId: conn.id,
          ownerId: conn.ownerId,
          actingUserId: userId,
          reason: String(req.body.reason),
        },
        'success',
      );
      const updated = deps.connectionRepo.resolveConnection(conn.id)!;
      res.json({ connection: presentConnection(updated) });
    } catch (e) {
      logger.warn(`[ssh:api] admin disable failed err=${String(e)}`);
      jsonError(res, 500, 'disable_failed');
    }
  });

  router.patch('/connections/:id/enable', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      const ok = deps.connectionRepo.enableByAdmin(conn.id);
      if (!ok) { jsonError(res, 404, 'not_found'); return; }
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.connection.enable',
          entityType: 'ssh_connection',
          entityId: conn.id,
          connectionId: conn.id,
          ownerId: conn.ownerId,
          actingUserId: userId,
          reason: String(req.body.reason),
        },
        'success',
      );
      const updated = deps.connectionRepo.resolveConnection(conn.id)!;
      res.json({ connection: presentConnection(updated) });
    } catch (e) {
      logger.warn(`[ssh:api] admin enable failed err=${String(e)}`);
      jsonError(res, 500, 'enable_failed');
    }
  });

  router.delete('/connections/:id', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      const auditId = deps.auditRepo.begin({
        action: 'ssh.connection.delete',
        entityType: 'ssh_connection',
        entityId: conn.id,
        connectionId: conn.id,
        ownerId: conn.ownerId,
        actingUserId: userId,
        reason: String(req.body.reason),
      });
      const ok = deps.connectionRepo.delete(conn.id);
      if (!ok) {
        deps.auditRepo.complete(auditId, 'failed', { err: 'no_changes' });
        jsonError(res, 404, 'not_found');
        return;
      }
      deps.auditRepo.complete(auditId, 'success');
      res.json({ ok: true });
    } catch (e) {
      logger.warn(`[ssh:api] admin delete failed err=${String(e)}`);
      jsonError(res, 500, 'delete_failed');
    }
  });

  router.post('/connections/:id/force-unlock', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const decision = deps.forceUnlockLimiter.check(userId);
      if (!decision.allowed) {
        if (decision.retryAfterSeconds !== undefined) {
          res.setHeader('Retry-After', String(decision.retryAfterSeconds));
        }
        jsonError(res, 429, 'rate_limited', { retryAfterSeconds: decision.retryAfterSeconds });
        return;
      }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      const removed = deps.abuseRepo.reset(`conn:${conn.id}`);
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.abuse.unlock_manual',
          entityType: 'ssh_connection',
          entityId: conn.id,
          connectionId: conn.id,
          ownerId: conn.ownerId,
          actingUserId: userId,
          reason: String(req.body.reason),
          detail: { removed },
        },
        'success',
      );
      res.json({ ok: true, removed });
    } catch (e) {
      logger.warn(`[ssh:api] admin force-unlock failed err=${String(e)}`);
      jsonError(res, 500, 'unlock_failed');
    }
  });

  // POST /api/ssh/admin/globals — create a global connection (owner_id=NULL).
  router.post('/globals', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    const userId = deps.getUserId(req);
    if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
    const reasonErr = validateReason(req.body?.reason);
    if (reasonErr) { jsonError(res, 400, reasonErr); return; }
    const body = req.body ?? {};
    const label = safeString(body.label, 200);
    const host = safeString(body.host, 255);
    const port = safePort(body.port);
    const username = safeString(body.username, 64);
    const denyPatterns = safeOptionalString(body.commandDenyPatterns, 4096);
    const allowPatterns = safeOptionalString(body.commandAllowPatterns, 4096);
    const allowRemoteUnrestricted = body.allowRemoteUnrestricted === true || body.allowRemoteUnrestricted === 1;
    const allowPrivateAddresses = body.allowPrivateAddresses === true || body.allowPrivateAddresses === 1;

    // remote_path_prefix is required UNLESS allow_remote_unrestricted is set.
    let remotePathPrefix: string | null;
    if (allowRemoteUnrestricted) {
      // Stored prefix is '/' (sandbox-effectively-disabled).
      remotePathPrefix = '/';
    } else {
      remotePathPrefix = safePathPrefix(body.remotePathPrefix);
    }

    // Keypair source: 'provided' (admin uploads PEM) or 'generate' (orchestrator
    // creates a fresh keypair; the public key is returned exactly once).
    const keypairSource = body.keypairSource === 'generate' ? 'generate' : 'provided';
    let pemBuf: Buffer;
    let passBuf: Buffer | null;
    if (keypairSource === 'generate') {
      const keyType = body.generateKeyType === 'rsa-4096' ? 'rsa-4096' : 'ed25519';
      const generated = deps.generateKeypair(keyType);
      pemBuf = generated.privateKeyPem;
      passBuf = null;
    } else {
      const privateKey = typeof body.privateKeyPem === 'string' ? body.privateKeyPem : null;
      const passphrase = typeof body.passphrase === 'string' ? body.passphrase : null;
      if (!privateKey) {
        jsonError(res, 400, 'invalid_input', {
          required: ['label', 'host', 'port (1-65535)', 'username', 'privateKeyPem', 'remotePathPrefix (or allowRemoteUnrestricted=true)'],
        });
        return;
      }
      pemBuf = Buffer.from(privateKey, 'utf8');
      passBuf = passphrase ? Buffer.from(passphrase, 'utf8') : null;
    }

    if (!label || !host || port === null || !username || !remotePathPrefix) {
      pemBuf.fill(0);
      if (passBuf) passBuf.fill(0);
      jsonError(res, 400, 'invalid_input', {
        required: ['label', 'host', 'port (1-65535)', 'username', 'privateKeyPem', 'remotePathPrefix (or allowRemoteUnrestricted=true)'],
      });
      return;
    }
    if (denyPatterns === null) {
      pemBuf.fill(0);
      if (passBuf) passBuf.fill(0);
      jsonError(res, 400, 'invalid_command_deny_patterns'); return;
    }
    if (allowPatterns === null) {
      pemBuf.fill(0);
      if (passBuf) passBuf.fill(0);
      jsonError(res, 400, 'invalid_command_allow_patterns'); return;
    }

    let encrypted: SshEncryptResult;
    try {
      encrypted = deps.encryptKeyMaterial(null, pemBuf, passBuf);
    } catch (e) {
      pemBuf.fill(0);
      if (passBuf) passBuf.fill(0);
      logger.warn(`[ssh:api] admin global encrypt failed err=${String(e)}`);
      jsonError(res, 500, 'encrypt_failed');
      return;
    }
    pemBuf.fill(0);
    if (passBuf) passBuf.fill(0);

    try {
      const conn = deps.connectionRepo.create({
        ownerId: null,
        label, host, port, username,
        privateKeyEnc: encrypted.blob,
        passphraseEnc: encrypted.passphraseBlob,
        keyVersion: encrypted.keyVersion,
        keyFingerprint: encrypted.fingerprint,
        remotePathPrefix,
        allowRemoteUnrestricted,
        allowPrivateAddresses,
        commandDenyPatterns: denyPatterns ?? null,
        commandAllowPatterns: allowPatterns ?? null,
      });
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.connection.upsert',
          entityType: 'ssh_connection',
          entityId: conn.id,
          connectionId: conn.id,
          ownerId: null,
          actingUserId: userId,
          reason: String(body.reason),
          detail: { op: 'create', scope: 'global', allowRemoteUnrestricted, allowPrivateAddresses, keypairSource },
        },
        'success',
      );
      res.status(201).json({
        connection: presentConnection(conn),
        publicKey: encrypted.publicKey,
      });
    } catch (e) {
      logger.warn(`[ssh:api] admin global create failed err=${String(e)}`);
      jsonError(res, 500, 'create_failed');
    }
  });

  router.patch('/globals/:id', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      if (conn.ownerId !== null) { jsonError(res, 400, 'not_global'); return; }
      const body = req.body ?? {};
      const patch: Parameters<SshConnectionRepo['update']>[1] = {};
      if (body.label !== undefined) {
        const v = safeString(body.label, 200);
        if (v === null) { jsonError(res, 400, 'invalid_label'); return; }
        patch.label = v;
      }
      if (body.host !== undefined) {
        const v = safeString(body.host, 255);
        if (v === null) { jsonError(res, 400, 'invalid_host'); return; }
        patch.host = v;
      }
      if (body.port !== undefined) {
        const v = safePort(body.port);
        if (v === null) { jsonError(res, 400, 'invalid_port'); return; }
        patch.port = v;
      }
      if (body.username !== undefined) {
        const v = safeString(body.username, 64);
        if (v === null) { jsonError(res, 400, 'invalid_username'); return; }
        patch.username = v;
      }
      if (body.remotePathPrefix !== undefined) {
        const v = safePathPrefix(body.remotePathPrefix);
        if (v === null) { jsonError(res, 400, 'invalid_remote_path_prefix'); return; }
        patch.remotePathPrefix = v;
      }
      if (body.commandDenyPatterns !== undefined) {
        const v = safeOptionalString(body.commandDenyPatterns, 4096);
        if (v === null) { jsonError(res, 400, 'invalid_command_deny_patterns'); return; }
        patch.commandDenyPatterns = v ?? null;
      }
      if (body.commandAllowPatterns !== undefined) {
        const v = safeOptionalString(body.commandAllowPatterns, 4096);
        if (v === null) { jsonError(res, 400, 'invalid_command_allow_patterns'); return; }
        patch.commandAllowPatterns = v ?? null;
      }
      if (body.allowRemoteUnrestricted !== undefined) {
        patch.allowRemoteUnrestricted = body.allowRemoteUnrestricted === true || body.allowRemoteUnrestricted === 1;
      }
      if (body.allowPrivateAddresses !== undefined) {
        patch.allowPrivateAddresses = body.allowPrivateAddresses === true || body.allowPrivateAddresses === 1;
      }
      if (typeof body.privateKeyPem === 'string') {
        let pemBuf = Buffer.from(body.privateKeyPem, 'utf8');
        let passBuf = typeof body.passphrase === 'string' ? Buffer.from(body.passphrase, 'utf8') : null;
        try {
          const enc = deps.encryptKeyMaterial(null, pemBuf, passBuf);
          patch.privateKeyEnc = enc.blob;
          patch.passphraseEnc = enc.passphraseBlob;
          patch.keyVersion = enc.keyVersion;
          patch.keyFingerprint = enc.fingerprint;
        } finally {
          pemBuf.fill(0);
          if (passBuf) passBuf.fill(0);
        }
      }
      const ok = deps.connectionRepo.update(conn.id, patch);
      if (!ok) { jsonError(res, 404, 'not_found'); return; }
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.connection.upsert',
          entityType: 'ssh_connection',
          entityId: conn.id,
          connectionId: conn.id,
          ownerId: null,
          actingUserId: userId,
          reason: String(req.body.reason),
          detail: { op: 'update', scope: 'global', fields: Object.keys(patch) },
        },
        'success',
      );
      const updated = deps.connectionRepo.resolveConnection(conn.id)!;
      res.json({ connection: presentConnection(updated) });
    } catch (e) {
      logger.warn(`[ssh:api] admin global patch failed err=${String(e)}`);
      jsonError(res, 500, 'update_failed');
    }
  });

  router.delete('/globals/:id', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const conn = deps.connectionRepo.resolveConnection(req.params.id);
      if (!conn) { jsonError(res, 404, 'not_found'); return; }
      if (conn.ownerId !== null) { jsonError(res, 400, 'not_global'); return; }
      const auditId = deps.auditRepo.begin({
        action: 'ssh.connection.delete',
        entityType: 'ssh_connection',
        entityId: conn.id,
        connectionId: conn.id,
        ownerId: null,
        actingUserId: userId,
        reason: String(req.body.reason),
      });
      const ok = deps.connectionRepo.delete(conn.id);
      if (!ok) {
        deps.auditRepo.complete(auditId, 'failed', { err: 'no_changes' });
        jsonError(res, 404, 'not_found');
        return;
      }
      deps.auditRepo.complete(auditId, 'success');
      res.json({ ok: true });
    } catch (e) {
      logger.warn(`[ssh:api] admin global delete failed err=${String(e)}`);
      jsonError(res, 500, 'delete_failed');
    }
  });

  router.get('/grants', deps.requireAdmin, (req, res) => {
    try {
      const limit = safeLimit(req.query.limit, 100, 1000);
      const rows = deps.db.prepare(
        `SELECT * FROM ssh_connection_grants ORDER BY created_at DESC LIMIT ?`,
      ).all(limit) as Array<{
        id: string; connection_id: string; subject_type: SshGrantSubjectType; subject_id: string;
        piece_name: string | null; applies_to_all_pieces: number; granted_by_user_id: string;
        reason: string; expires_at: string | null; created_at: string;
      }>;
      const grants = rows.map((r) => ({
        id: r.id,
        connectionId: r.connection_id,
        subjectType: r.subject_type,
        subjectId: r.subject_id,
        pieceName: r.piece_name,
        appliesToAllPieces: r.applies_to_all_pieces === 1,
        grantedByUserId: r.granted_by_user_id,
        reason: r.reason,
        expiresAt: r.expires_at,
        createdAt: r.created_at,
      }));
      res.json({ grants });
    } catch (e) {
      logger.warn(`[ssh:api] admin list grants failed err=${String(e)}`);
      jsonError(res, 500, 'list_grants_failed');
    }
  });

  router.post('/grants', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const body = req.body ?? {};
      const reasonErr = validateReason(body.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const connectionId = safeUuid(body.connectionId);
      const subjectType = safeSubjectType(body.subjectType);
      const subjectId = safeString(body.subjectId, 128);
      const appliesToAllPieces = body.appliesToAllPieces === true || body.appliesToAllPieces === 1;
      const pieceName = safeOptionalString(body.pieceName, 64);
      const expiresAt = safeExpiresAt(body.expiresAt);
      if (!connectionId || !subjectType || !subjectId) {
        jsonError(res, 400, 'invalid_input', {
          required: ['connectionId', 'subjectType ("user"|"org")', 'subjectId', 'reason'],
        });
        return;
      }
      if (pieceName === null) { jsonError(res, 400, 'invalid_piece_name'); return; }
      if (expiresAt === null) { jsonError(res, 400, 'invalid_expires_at'); return; }
      if (!appliesToAllPieces && (!pieceName || pieceName.length === 0)) {
        jsonError(res, 400, 'piece_name_required_unless_applies_to_all'); return;
      }
      if (appliesToAllPieces && pieceName !== undefined && pieceName.length > 0) {
        jsonError(res, 400, 'piece_name_conflicts_with_applies_to_all'); return;
      }
      // Connection must exist before granting.
      const conn = deps.connectionRepo.resolveConnection(connectionId);
      if (!conn) { jsonError(res, 404, 'connection_not_found'); return; }
      let grant: SshGrant;
      try {
        grant = deps.grantsRepo.create({
          connectionId,
          subjectType,
          subjectId,
          pieceName: appliesToAllPieces ? null : (pieceName ?? null),
          appliesToAllPieces,
          grantedByUserId: userId,
          reason: String(body.reason),
          expiresAt,
        });
      } catch (e) {
        jsonError(res, 400, 'grant_create_failed', { detail: String(e) }); return;
      }
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.grant.create',
          entityType: 'ssh_grant',
          entityId: grant.id,
          connectionId: conn.id,
          ownerId: conn.ownerId,
          actingUserId: userId,
          reason: String(body.reason),
          detail: { subjectType, subjectId, pieceName: grant.pieceName, appliesToAllPieces },
        },
        'success',
      );
      res.status(201).json({ grant: presentGrant(grant) });
    } catch (e) {
      logger.warn(`[ssh:api] admin grant create failed err=${String(e)}`);
      jsonError(res, 500, 'grant_create_failed');
    }
  });

  router.delete('/grants/:id', deps.requireAdmin, (req, res) => {
    if (maintenance503(deps.maintenance, res)) return;
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      const grant = deps.grantsRepo.getById(req.params.id);
      if (!grant) { jsonError(res, 404, 'not_found'); return; }
      const ok = deps.grantsRepo.delete(grant.id);
      if (!ok) { jsonError(res, 404, 'not_found'); return; }
      // Kick any active console-WS viewers whose access depended on this grant.
      // user-subject grants map 1:1 to a single userId; org-subject grants are
      // deferred (next attach will be denied; existing viewers stay until the
      // session ends or the org-member's WS reconnects).
      let kicked: number | void = 0;
      if (grant.subjectType === 'user' && deps.onAccessRevoked) {
        kicked = deps.onAccessRevoked({ connectionId: grant.connectionId, userId: grant.subjectId });
      }
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.grant.delete',
          entityType: 'ssh_grant',
          entityId: grant.id,
          connectionId: grant.connectionId,
          actingUserId: userId,
          reason: String(req.body.reason),
          detail: {
            subjectType: grant.subjectType,
            subjectId: grant.subjectId,
            pieceName: grant.pieceName,
            viewersKicked: typeof kicked === 'number' ? kicked : 0,
          },
        },
        'success',
      );
      res.json({ ok: true });
    } catch (e) {
      logger.warn(`[ssh:api] admin grant delete failed err=${String(e)}`);
      jsonError(res, 500, 'grant_delete_failed');
    }
  });

  // POST /api/ssh/admin/rotate-master-key — stub for v1 (Phase 5).
  // Sets the maintenance flag and audits the intent. The actual DEK re-wrap
  // job is deferred to a follow-up PR per Phase 5 design note (line 728).
  // Returns 501 in the response body but 202 status so the UI can show a
  // banner; UI Phase 6 will key off the maintenance snapshot.
  router.post('/rotate-master-key', deps.requireAdmin, (req, res) => {
    try {
      const userId = deps.getUserId(req);
      if (!userId) { jsonError(res, 401, 'unauthorized'); return; }
      const reasonErr = validateReason(req.body?.reason);
      if (reasonErr) { jsonError(res, 400, reasonErr); return; }
      if (deps.maintenance.isActive()) {
        jsonError(res, 409, 'already_in_progress', { snapshot: deps.maintenance.snapshot() });
        return;
      }
      const jobId = `rotate-${Date.now().toString(36)}`;
      deps.maintenance.enter(String(req.body.reason), jobId);
      deps.auditRepo.beginAndComplete(
        {
          action: 'ssh.master_key.rotate.start',
          actingUserId: userId,
          reason: String(req.body.reason),
          detail: { jobId, status: 'stub', note: 'rotation job not implemented in v1; only maintenance flag set' },
        },
        'success',
      );
      res.status(202).json({
        jobId,
        status: 'maintenance_set',
        detail: 'maintenance flag is now active; actual DEK re-wrap is not implemented in v1',
        notImplemented: true,
      });
    } catch (e) {
      logger.warn(`[ssh:api] admin rotate-master-key failed err=${String(e)}`);
      jsonError(res, 500, 'rotate_failed');
    }
  });

  router.get('/rotate-master-key/:jobId', deps.requireAdmin, (req, res) => {
    try {
      const snap = deps.maintenance.snapshot();
      if (!snap.active || snap.jobId !== req.params.jobId) {
        jsonError(res, 404, 'not_found_or_completed', { snapshot: snap });
        return;
      }
      res.json({
        jobId: snap.jobId,
        status: 'in_progress',
        startedAt: snap.enteredAt,
        progress: { note: 'v1 stub: no rewrap performed' },
        notImplemented: true,
      });
    } catch (e) {
      logger.warn(`[ssh:api] admin rotate-master-key get failed err=${String(e)}`);
      jsonError(res, 500, 'rotate_get_failed');
    }
  });

  // GET /api/ssh/admin/audit — cross-user audit query.
  router.get('/audit', deps.requireAdmin, (req, res) => {
    try {
      const limit = safeLimit(req.query.limit, 100, 1000);
      const action = typeof req.query.action === 'string' ? req.query.action : null;
      const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId : null;
      const connectionId = typeof req.query.connectionId === 'string' ? req.query.connectionId : null;
      const outcome = typeof req.query.outcome === 'string' ? req.query.outcome : null;

      const where: string[] = [];
      const params: unknown[] = [];
      if (action) { where.push('action = ?'); params.push(action); }
      if (ownerId) { where.push('owner_id = ?'); params.push(ownerId); }
      if (connectionId) { where.push('connection_id = ?'); params.push(connectionId); }
      if (outcome) { where.push('outcome = ?'); params.push(outcome); }
      const whereClause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
      const sql = `SELECT * FROM ssh_audit_log ${whereClause} ORDER BY started_at DESC LIMIT ?`;
      params.push(limit);
      const rows = deps.db.prepare(sql).all(...params) as Array<{
        id: number; action: string; entity_type: string | null; entity_id: string | null;
        connection_id: string | null; owner_id: string | null; acting_user_id: string | null;
        job_id: string | null; piece_name: string | null; outcome: string;
        reason: string | null; detail: string | null; started_at: string; completed_at: string | null;
      }>;
      const audit = rows.map((r) => ({
        id: r.id,
        action: r.action,
        entityType: r.entity_type,
        entityId: r.entity_id,
        connectionId: r.connection_id,
        ownerId: r.owner_id,
        actingUserId: r.acting_user_id,
        jobId: r.job_id,
        pieceName: r.piece_name,
        outcome: r.outcome,
        reason: r.reason,
        detail: r.detail ? JSON.parse(r.detail) : null,
        startedAt: r.started_at,
        completedAt: r.completed_at,
      }));
      res.json({ audit });
    } catch (e) {
      logger.warn(`[ssh:api] admin audit list failed err=${String(e)}`);
      jsonError(res, 500, 'audit_failed');
    }
  });

  return router;
}
