-- =========================================================
-- Reporting views para Grafana UCEPSA demo
-- Grafana debe consultar preferentemente este schema.
-- =========================================================

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.energy_latest AS
SELECT
    ts,
    ingest_ts,
    age_s,
    tenant,
    site,
    asset,
    meter_model,
    meter_id,
    machine_id,
    voltage_l1_v,
    current_l1_a,
    power_total_kw,
    frequency_hz,
    import_kwh,
    export_kwh,
    comm_ok,
    error_text,
    comm_risk_level,
    comm_status
FROM mv_hot.edge_oee_eastron_dashboard
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.energy_diagnosis AS
SELECT *
FROM mv_hot.edge_oee_eastron_diagnosis_latest;

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.live_telemetry AS
SELECT *
FROM mv_hot.edge_oee_live_telemetry
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.latest_machine_snapshot AS
SELECT *
FROM mv_hot.edge_oee_latest_machine_snapshot
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.node_events_recent AS
SELECT *
FROM mv_hot.edge_oee_node_events_recent
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.machine_state_latest AS
SELECT *
FROM mv_hot.edge_oee_machine_state_latest
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.open_stops AS
SELECT *
FROM mv_hot.edge_oee_open_stops
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.stops_recent AS
SELECT *
FROM mv_hot.edge_oee_stops_recent
WHERE asset = 'revpi_oee_node_01';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.stop_summary AS
SELECT *
FROM mv_hot.edge_oee_stop_summary_demo;

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.machine_targets AS
SELECT *
FROM mv_hot.edge_oee_machine_targets
WHERE machine_id = 'C_DEMO';

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.energy_power_timeseries AS
SELECT
    ingest_ts AS time,
    ROUND((power_total_kw * 1000)::numeric, 2) AS power_w
FROM mv_hot.edge_oee_eastron_readings
WHERE asset = 'revpi_oee_node_01'
ORDER BY ingest_ts;

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.energy_import_timeseries AS
SELECT
    ingest_ts AS time,
    ROUND((import_kwh * 1000)::numeric, 2) AS import_wh
FROM mv_hot.edge_oee_eastron_readings
WHERE asset = 'revpi_oee_node_01'
ORDER BY ingest_ts;

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.cycle_rate_timeseries AS
SELECT
    ts AS time,
    cycle_rate_ppm,
    10.0::numeric AS target_cycle_rate_ppm
FROM mv_hot.edge_oee_live_telemetry
WHERE asset = 'revpi_oee_node_01'
  AND cycle_rate_ppm IS NOT NULL
ORDER BY ts;
