/** Parse audit log detail JSON for server batch jobs (written by server_batch_service). */

export interface AuditBatchJobDetail {
  job_id: number
  summary: string
  success?: number
  failed?: number
  total?: number
  failures?: Array<{ server_name: string; error: string }>
}

const BATCH_AUDIT_ACTIONS = new Set([
  'batch_install_agent',
  'batch_upgrade_agent',
  'batch_uninstall_agent',
  'batch_detect_path',
  'batch_health_check',
  'batch_update_category',
  'batch_server_op',
])

export function isBatchJobAuditAction(action: string): boolean {
  return BATCH_AUDIT_ACTIONS.has(action)
}

export function parseAuditBatchDetail(detail: string | null | undefined): AuditBatchJobDetail | null {
  const raw = (detail || '').trim()
  if (!raw.startsWith('{')) return null
  try {
    const obj = JSON.parse(raw) as AuditBatchJobDetail
    if (typeof obj.job_id !== 'number' || !obj.summary) return null
    return obj
  } catch {
    return null
  }
}

export function formatAuditBatchDetailText(parsed: AuditBatchJobDetail): string {
  const parts = [parsed.summary]
  const failures = parsed.failures || []
  if (failures.length) {
    const names = failures.slice(0, 3).map((f) => f.server_name).join('、')
    parts.push(`失败: ${names}${failures.length > 3 ? '…' : ''}`)
  }
  return parts.join(' · ')
}
