-- Daily aggregation of electricity prices + demand
CREATE MATERIALIZED VIEW electricity_prices_daily AS
SELECT
  region_id,
  date_trunc('day', timestamp) AS day,
  AVG(price_mwh) AS avg_price,
  MAX(price_mwh) AS max_price,
  MIN(price_mwh) AS min_price,
  AVG(demand_mw) AS avg_demand,
  MAX(demand_mw) AS peak_demand
FROM electricity_prices
GROUP BY region_id, date_trunc('day', timestamp);

CREATE UNIQUE INDEX electricity_prices_daily_region_day
  ON electricity_prices_daily (region_id, day);

-- Weekly aggregation of electricity prices + demand
CREATE MATERIALIZED VIEW electricity_prices_weekly AS
SELECT
  region_id,
  date_trunc('week', timestamp) AS week,
  AVG(price_mwh) AS avg_price,
  MAX(price_mwh) AS max_price,
  MIN(price_mwh) AS min_price,
  AVG(demand_mw) AS avg_demand,
  MAX(demand_mw) AS peak_demand
FROM electricity_prices
GROUP BY region_id, date_trunc('week', timestamp);

CREATE UNIQUE INDEX electricity_prices_weekly_region_week
  ON electricity_prices_weekly (region_id, week);

-- Daily aggregation of generation mix
CREATE MATERIALIZED VIEW generation_mix_daily AS
SELECT
  region_id,
  fuel_type,
  date_trunc('day', timestamp) AS day,
  AVG(generation_mw) AS avg_generation,
  MAX(generation_mw) AS peak_generation
FROM generation_mix
GROUP BY region_id, fuel_type, date_trunc('day', timestamp);

CREATE UNIQUE INDEX generation_mix_daily_region_fuel_day
  ON generation_mix_daily (region_id, fuel_type, day);

-- Weekly aggregation of generation mix
CREATE MATERIALIZED VIEW generation_mix_weekly AS
SELECT
  region_id,
  fuel_type,
  date_trunc('week', timestamp) AS week,
  AVG(generation_mw) AS avg_generation,
  MAX(generation_mw) AS peak_generation
FROM generation_mix
GROUP BY region_id, fuel_type, date_trunc('week', timestamp);

CREATE UNIQUE INDEX generation_mix_weekly_region_fuel_week
  ON generation_mix_weekly (region_id, fuel_type, week);

-- BRIN index for time-series range scans on large tables
CREATE INDEX electricity_prices_timestamp_brin
  ON electricity_prices USING brin (timestamp);

CREATE INDEX generation_mix_timestamp_brin
  ON generation_mix USING brin (timestamp);
