-- @param {DateTime} $1:startDate
-- @param {DateTime} $2:endDate
-- @param {String} $3:regionCode - pass 'ALL' to return all regions
SELECT
  r.code AS region_code,
  r.name AS region_name,
  ep.timestamp AS day,
  ep.demand_mw AS avg_demand,
  ep.demand_mw AS peak_demand,
  COALESCE(dc.datacenter_count, 0)::INT AS datacenter_count,
  COALESCE(dc.total_dc_capacity_mw, 0) AS total_dc_capacity_mw
FROM electricity_prices ep
JOIN grid_regions r ON ep.region_id = r.id
LEFT JOIN (
  SELECT region_id, COUNT(*)::INT AS datacenter_count,
    COALESCE(SUM(capacity_mw), 0) AS total_dc_capacity_mw
  FROM datacenters GROUP BY region_id
) dc ON dc.region_id = r.id
WHERE ep.timestamp BETWEEN $1 AND $2
  AND ($3 = 'ALL' OR r.code = $3)
ORDER BY r.code, ep.timestamp
