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

export interface FilterOptions {
  statusFilter: string
  resourceTypeFilter: string
  hostnameFilter: string
  priorityFilter: string
  searchTerm: string
}

export const filterRequests = (requests: HTTPRequest[], filters: FilterOptions): HTTPRequest[] => {
  return requests.filter(request => {
    // Status filter
    if (filters.statusFilter !== 'all') {
      const status = request.statusCode
      if (filters.statusFilter === '2xx' && (!status || status < 200 || status >= 300)) return false
      if (filters.statusFilter === '3xx' && (!status || status < 300 || status >= 400)) return false
      if (filters.statusFilter === '4xx' && (!status || status < 400 || status >= 500)) return false
      if (filters.statusFilter === '5xx' && (!status || status < 500)) return false
    }

    // Resource type filter
    if (filters.resourceTypeFilter !== 'all' && request.resourceType !== filters.resourceTypeFilter) {
      return false
    }

    // Hostname filter
    if (filters.hostnameFilter !== 'all' && request.hostname !== filters.hostnameFilter) {
      return false
    }

    // Priority filter
    if (filters.priorityFilter !== 'all' && request.priority !== filters.priorityFilter) {
      return false
    }

    // Search filter
    if (filters.searchTerm && !request.url.toLowerCase().includes(filters.searchTerm.toLowerCase())) {
      return false
    }

    return true
  })
}

export const paginateRequests = (requests: HTTPRequest[], currentPage: number): HTTPRequest[] => {
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
  const endIndex = startIndex + ITEMS_PER_PAGE
  return requests.slice(startIndex, endIndex)
}

export const createTimelineEntries = (requests: HTTPRequest[]): Array<{ request: HTTPRequest; timing: any }> => {
  return requests
    .filter(request => request.timing.startOffset !== undefined)
    .map(request => ({
      request,
      timing: {
        startOffset: request.timing.startOffset,
        duration: request.timing.duration || 0,
        queueTime: request.timing.queueTime || 0,
        serverLatency: request.timing.serverLatency || 0
      }
    }))
    .sort((a, b) => (a.timing.startOffset || 0) - (b.timing.startOffset || 0))
}

export const getUniqueValues = <T>(items: T[], key: keyof T): string[] => {
  const values = items.map(item => String(item[key])).filter(Boolean)
  return Array.from(new Set(values)).sort()
}

export const getResourceTypes = (requests: HTTPRequest[]): string[] => {
  return getUniqueValues(requests, 'resourceType')
}

export const getProtocols = (requests: HTTPRequest[]): string[] => {
  return getUniqueValues(requests, 'protocol')
}

export const getHostnames = (requests: HTTPRequest[]): string[] => {
  return getUniqueValues(requests, 'hostname')
}

export const getPriorities = (requests: HTTPRequest[]): string[] => {
  return getUniqueValues(requests, 'priority')
}