import {RFC_1928_VERSION} from './constants'
import {EndConnectionParameters} from '../types/end-socket-connection'

export function endConnection({socket, response, args}: EndConnectionParameters) {
  // either use the raw buffer (if available) or create a new one
  const responseBuffer = args.requestBuffer || Buffer.allocUnsafe(2)

  if (!args.requestBuffer) {
    responseBuffer[0] = RFC_1928_VERSION
  }

  responseBuffer[1] = response

  // respond then end the connection
  try {
    socket.end(responseBuffer)
  } catch (ex) {
    socket.destroy()
  }
}
