import { query } from '../../../utils/db'

export default defineEventHandler(async (event) => {
  const queryParams = getQuery(event)
  const targetId = queryParams.target_id as string
  const period = (queryParams.period as string) || '1h'
  
  if (!targetId) {
    throw createError({
      statusCode: 400,
      message: 'target_id is required'
    })
  }
  
  const periodMap: Record<string, string> = {
    '1h': '1 hour',
    '2h': '2 hours',
    '3h': '3 hours',
    '4h': '4 hours',
    '5h': '5 hours',
    '6h': '6 hours',
    '12h': '12 hours',
    '18h': '18 hours',
    '24h': '24 hours',
    '7d': '7 days',
    '30d': '30 days'
  }
  
  const interval = periodMap[period] || '1 hour'
  
  const snapshots = await query(`
    SELECT 
      snapshot_id,
      cpu_percent,
      cpu_temp,
      load_percent,
      memory_percent,
      memory_total,
      memory_used,
      memory_free,
      swap_percent,
      swap_total,
      swap_used,
      is_online,
      collected_at
    FROM server_snapshots
    WHERE target_id = $1
      AND collected_at::timestamp >= NOW() - INTERVAL '${interval}'
    ORDER BY collected_at ASC
  `, [targetId])
  
  return {
    target_id: targetId,
    period,
    data: snapshots
  }
})
