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

export default defineEventHandler(async () => {
  const stats = await query(`
    SELECT 
      t.physical_location,
      COUNT(DISTINCT t.target_id) as server_count,
      ROUND(AVG(s.cpu_temp)::numeric, 1) as avg_temp,
      ROUND(SUM(n.speed_recv)::numeric, 0) as total_rx,
      ROUND(SUM(n.speed_sent)::numeric, 0) as total_tx
    FROM server_targets t
    LEFT JOIN server_snapshots s ON t.target_id = s.target_id 
      AND s.collected_at::timestamp >= NOW() - INTERVAL '10 minutes'
    LEFT JOIN server_networks n ON t.target_id = n.target_id 
      AND n.collected_at::timestamp >= NOW() - INTERVAL '10 minutes'
    WHERE t.is_active = 1
    GROUP BY t.physical_location
    ORDER BY t.physical_location
  `)
  
  return stats.map((row: any) => ({
    location: row.physical_location || '미지정',
    serverCount: Number(row.server_count) || 0,
    avgTemp: row.avg_temp ? parseFloat(row.avg_temp) : null,
    totalRx: Number(row.total_rx) || 0,
    totalTx: Number(row.total_tx) || 0
  }))
})
