import type { Client } from 'ssh2'

export function execCommand(
  client: Client,
  command: string,
  timeoutMs = 15000,
): Promise<{ stdout: string; stderr: string; code: number | null }> {
  return new Promise((resolve, reject) => {
    client.exec(command, { pty: false }, (err, stream) => {
      if (err) return reject(err)
      let stdout = ''
      let stderr = ''
      const timer = setTimeout(() => {
        stream.removeAllListeners()
        stream.destroy()
        reject(new Error(`Command timed out: ${command}`))
      }, timeoutMs)
      stream.on('data', (chunk: Buffer) => (stdout += chunk.toString('utf8')))
      stream.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString('utf8')))
      stream.on('close', (code: number | null) => {
        clearTimeout(timer)
        resolve({ stdout, stderr, code })
      })
      stream.on('error', (e: Error) => {
        clearTimeout(timer)
        reject(e)
      })
    })
  })
}

export function kibToGiB(kib: number): number {
  return kib / (1024 * 1024)
}

export function toFixedNum(n: number | null | undefined, digits = 2): number | null {
  if (n === null || n === undefined || !Number.isFinite(n)) return null
  return Number(n.toFixed(digits))
}
