-- PostgREST ems_anon: SELECT na views (repeatable R__072 – po ostatních vw_* v pořadí Flyway).
--
-- Po importu DB dumpu bez cluster rolí často chybí samotná role; V009 pak na cílovém
-- clusteru neběžela. Tento blok je idempotentní a při změně souboru znovu spáruje granty.
--
-- GRANT SELECT na Timescale hypertably / continuous aggregate v repeatable NEpatří: při
-- opakovaném běhu Flyway Timescale propaguje oprávnění na chunky; u nekonzistentního
-- katalogu (_hyper_* „chunk not found“) migrace spadne. Oprávnění na hypertabulky zůstávají
-- ve verzovaných migracích (V009, …); PostgREST čte přes views s security_invoker = false.

DO $$ BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'ems_anon') THEN
    CREATE ROLE ems_anon NOLOGIN;
  END IF;
END $$;

GRANT USAGE ON SCHEMA ems TO ems_anon;

GRANT SELECT ON ems.vw_site_status           TO ems_anon;
GRANT SELECT ON ems.vw_site_effective_price  TO ems_anon;
GRANT SELECT ON ems.vw_latest_inverter       TO ems_anon;
GRANT SELECT ON ems.vw_latest_heat_pump      TO ems_anon;
GRANT SELECT ON ems.vw_audit_today_hourly    TO ems_anon;
GRANT SELECT ON ems.vw_audit_daily           TO ems_anon;
GRANT SELECT ON ems.vw_audit_weekly          TO ems_anon;
GRANT SELECT ON ems.vw_mode_log_recent       TO ems_anon;
GRANT SELECT ON ems.vw_operating_mode        TO ems_anon;
GRANT SELECT ON ems.vw_telemetry_hourly_7d    TO ems_anon;
GRANT SELECT ON ems.vw_telemetry_15m_7d       TO ems_anon;
GRANT SELECT ON ems.forecast_accuracy              TO ems_anon;
GRANT SELECT ON ems.site_pv_forecast_calibration TO ems_anon;
GRANT SELECT ON ems.site_pv_forecast_reference_day TO ems_anon;
GRANT SELECT ON ems.vw_forecast_accuracy_by_lead_time TO ems_anon;
GRANT SELECT ON ems.vw_forecast_accuracy_daily     TO ems_anon;
GRANT SELECT ON ems.consumption_baseline_stats     TO ems_anon;
GRANT SELECT ON ems.market_price_stats             TO ems_anon;
GRANT SELECT ON ems.tuv_usage_stats                TO ems_anon;
GRANT SELECT ON ems.baseline_load_forecast_accuracy TO ems_anon;
GRANT SELECT ON ems.vw_baseline_load_forecast_accuracy_daily TO ems_anon;
GRANT SELECT ON ems.vw_energy_flows_daily                  TO ems_anon;


grant select on ems.asset_heat_pump to ems_anon;
