import type { HTTPRequest } from '../types/httpRequest'
import { HIGHLIGHTING_CONFIG } from './httpRequestConstants'

export const addRequestPostProcessing = (
  sortedRequests: HTTPRequest[],
  analyzeQueueReason: (request: HTTPRequest, allRequests: HTTPRequest[]) => any,
  analyzeCDN: (request: HTTPRequest) => any
): HTTPRequest[] => {
  if (sortedRequests.length === 0) return sortedRequests

  // Calculate start time offsets from the first request
  const firstRequestTime = sortedRequests[0].timing.start
  
  sortedRequests.forEach(request => {
    // Add start time offset
    request.timing.startOffset = request.timing.start - firstRequestTime
    
    // Add queue analysis for requests with significant queue time
    if ((request.timing.queueTime || 0) >= HIGHLIGHTING_CONFIG.QUEUE_TIME.ANALYSIS_THRESHOLD) {
      request.queueAnalysis = analyzeQueueReason(request, sortedRequests)
    }
    
    // Add CDN analysis for requests with response headers
    if (request.responseHeaders && request.responseHeaders.length > 0) {
      request.cdnAnalysis = analyzeCDN(request)
    }
  })

  return sortedRequests
}