export type ServerSelectionEntry = { id: number | string } | number | string

function coerceServerId(value: unknown): number | null {
  if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
    return Math.trunc(value)
  }
  if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
    const n = Number(value.trim())
    return Number.isFinite(n) && n > 0 ? n : null
  }
  return null
}

/** Normalize v-data-table selection (Vuetify 4 modelValue: IDs, strings, or row objects). */
export function normalizeServerIds(selected: ServerSelectionEntry[]): number[] {
  const ids: number[] = []
  for (const item of selected) {
    const raw = typeof item === 'object' && item !== null && 'id' in item ? item.id : item
    const id = coerceServerId(raw)
    if (id !== null) ids.push(id)
  }
  return [...new Set(ids)]
}

export interface BatchAgentResultItem {
  server_id: number
  server_name: string
  success: boolean
  error?: string
  message?: string
}

export function countBatchSuccess(results: BatchAgentResultItem[] | undefined): number {
  return (results || []).filter(r => r.success).length
}
