import { RequestTime } from '../../../models/RequestTime.js'
import type { RequestStats } from '../CoreEngine.js'

/**
 * Creates HAR 1.2 timings object from stats.
 */
export function computeStats(stats: RequestStats): RequestTime {
  const {
    sentTime,
    messageStart,
    connectionTime = 0,
    lookupTime = 0,
    connectedTime,
    secureStartTime,
    secureConnectedTime,
    lastReceivedTime,
    firstReceiveTime,
    receivingTime,
  } = stats
  // in case the `send` event was not handled we use the `messageStart` as this is set when the request is created.
  const adjustedSentTime = sentTime || messageStart
  // when there was no body we check when the end time.
  const adjustedLastReceivedTime = lastReceivedTime || receivingTime
  const adjustedLookupTime = lookupTime || messageStart
  let send = adjustedSentTime && messageStart ? adjustedSentTime - messageStart : -1
  if (send < 0) {
    send = 0
  }
  const dns = lookupTime ? lookupTime - connectionTime : -1
  const connect = connectedTime && adjustedLookupTime ? connectedTime - adjustedLookupTime : -1
  let receive = adjustedLastReceivedTime && firstReceiveTime ? adjustedLastReceivedTime - firstReceiveTime : -1
  if (receive < 0) {
    receive = 0
  }
  let wait = firstReceiveTime && adjustedSentTime ? firstReceiveTime - adjustedSentTime : -1
  if (wait < 0) {
    wait = 0
  }
  let ssl = -1
  if (typeof secureStartTime === 'number' && typeof secureConnectedTime === 'number') {
    ssl = secureConnectedTime - secureStartTime
  }
  const result = new RequestTime()
  result.blocked = 0
  result.connect = connect
  result.receive = receive
  result.send = send
  result.wait = wait
  result.dns = dns
  result.ssl = ssl
  return result
}
