import type { Client, SFTPWrapper } from 'ssh2'
import { loadSshHost, connectTarget, type SshHost } from './connect.js'

/** Opens an ephemeral SSH+SFTP connection for a single operation, then tears it down.
 * Simpler than a pooled/long-lived session (which Termix uses) - acceptable at this
 * app's scale, and avoids a second connection-lifecycle to manage on top of the
 * terminal/tunnel ones. */
export function withSftp<T>(
  integrationId: number,
  fn: (sftp: SFTPWrapper, host: SshHost) => Promise<T>,
): Promise<T> {
  const target = loadSshHost(integrationId)
  if (!target) return Promise.reject(new Error('SSH integration not found'))

  return new Promise<T>((resolve, reject) => {
    let conn: Client | null = null
    let jumpConn: Client | null = null
    const cleanup = () => {
      conn?.end()
      jumpConn?.end()
    }
    const result = connectTarget(
      target,
      (client) => {
        conn = client
        client.sftp((err, sftp) => {
          if (err) {
            cleanup()
            reject(err)
            return
          }
          fn(sftp, target)
            .then((value) => {
              cleanup()
              resolve(value)
            })
            .catch((fnErr) => {
              cleanup()
              reject(fnErr)
            })
        })
      },
      (message) => {
        cleanup()
        reject(new Error(message))
      },
    )
    jumpConn = result.jumpConn
  })
}
