/**
 * Time range utility functions
 * Converts TimeRange enum to ISO 8601 date strings and labels
 */

import type { TimeRange, TimeRangeDates } from './types'

/**
 * Convert TimeRange to start and end ISO 8601 date strings
 * @param range - Time range enum (1h, 24h, 7d, 30d)
 * @returns Object with startDate and endDate as ISO 8601 strings
 */
export function getTimeRangeDates(range: TimeRange): TimeRangeDates {
  const end = new Date()
  const start = new Date()

  switch (range) {
    case '1h':
      start.setHours(start.getHours() - 1)
      break
    case '24h':
      start.setHours(start.getHours() - 24)
      break
    case '7d':
      start.setDate(start.getDate() - 7)
      break
    case '30d':
      start.setDate(start.getDate() - 30)
      break
  }

  return {
    startDate: start.toISOString(),
    endDate: end.toISOString()
  }
}

/**
 * Get a human-readable label for a time range
 * @param range - Time range enum
 * @returns Human-readable label
 */
export function getTimeRangeLabel(range: TimeRange): string {
  switch (range) {
    case '1h':
      return 'Last 1 hour'
    case '24h':
      return 'Last 24 hours'
    case '7d':
      return 'Last 7 days'
    case '30d':
      return 'Last 30 days'
  }
}

/**
 * Format a time-bucket timestamp for chart axis labels
 * @param timestamp - ISO 8601 timestamp string
 * @param granularity - 'hour' renders as "HH:MM" (24h), 'day' renders as "Mon DD"
 * @returns Formatted time string for display
 */
export function formatBucketTime(timestamp: string, granularity: 'hour' | 'day'): string {
  const date = new Date(timestamp)

  if (granularity === 'hour') {
    return date.toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    })
  }

  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric'
  })
}
