import { connect as netConnect } from 'node:net'
import type { IntegrationAdapter } from './types.js'

function requireConfig(config: Record<string, string>): string | null {
  if (!config.protocol || !['rdp', 'vnc', 'telnet'].includes(config.protocol)) return 'Missing or invalid protocol'
  if (!config.hostname) return 'Missing hostname'
  return null
}

function defaultPort(protocol: string): number {
  if (protocol === 'rdp') return 3389
  if (protocol === 'vnc') return 5900
  return 23
}

function probeTcp(host: string, port: number): Promise<void> {
  return new Promise((resolve, reject) => {
    const socket = netConnect({ host, port, timeout: 5000 })
    socket.once('connect', () => {
      socket.destroy()
      resolve()
    })
    socket.once('timeout', () => {
      socket.destroy()
      reject(new Error('Connection timed out'))
    })
    socket.once('error', (err) => reject(err))
  })
}

export const remoteDesktop: IntegrationAdapter = {
  async testConnection(config) {
    const missing = requireConfig(config)
    if (missing) return { ok: false, message: missing }
    const port = Number(config.port) || defaultPort(config.protocol)
    try {
      await probeTcp(config.hostname, port)
      return { ok: true, message: `${config.protocol.toUpperCase()} port reachable` }
    } catch (err) {
      return { ok: false, message: err instanceof Error ? err.message : 'Connection failed' }
    }
  },
}
