-- @param {DateTime} $1:startDate
-- @param {DateTime} $2:endDate
SELECT
  r.code as region_code, r.name as region_name,
  date_trunc('day', ep.timestamp) as day,
  AVG(ep.demand_mw) as avg_demand,
  MAX(ep.demand_mw) as peak_demand,
  COUNT(DISTINCT d.id)::INT as datacenter_count,
  COALESCE(SUM(DISTINCT d.capacity_mw), 0) as total_dc_capacity_mw
FROM grid_regions r
LEFT JOIN electricity_prices ep ON ep.region_id = r.id
  AND ep.timestamp BETWEEN $1 AND $2
LEFT JOIN datacenters d ON d.region_id = r.id
GROUP BY r.id, r.code, r.name, date_trunc('day', ep.timestamp)
ORDER BY r.code, day
