-- =============================================================
-- R__vw_latest_telemetry.sql
-- EMS Platform – aktuální stav všech zařízení per lokalita
-- Repeatable migration
-- =============================================================

-- security_invoker = false: oprávnění na podkladové hypertably nemusí mít ems_anon (PostgREST).
CREATE OR REPLACE VIEW ems.vw_latest_inverter
WITH (security_invoker = false)
AS
SELECT DISTINCT ON (t.inverter_id)
    t.site_id,
    t.inverter_id,
    inv.code                AS inverter_code,
    t.measured_at,
    t.pv_power_w,
    t.battery_soc_percent,
    t.battery_power_w,
    t.grid_power_w,
    t.load_power_w,
    t.inverter_temp_c,
    t.operating_mode,
    t.fault_code,
    now() - t.measured_at   AS data_age,
    t.pv1_power_w,
    t.pv2_power_w,
    t.gen_port_power_w,
    t.batt_charge_today_wh,
    t.batt_discharge_today_wh,
    t.run_state
FROM ems.telemetry_inverter t
JOIN ems.asset_inverter inv ON inv.id = t.inverter_id
ORDER BY t.inverter_id, t.measured_at DESC;

COMMENT ON VIEW ems.vw_latest_inverter IS
'Nejnovější telemetrická data pro každý střídač. Slouží pro real-time dashboard a health check.';

-- ------------------------------------------------------------

CREATE OR REPLACE VIEW ems.vw_latest_ev_charger
WITH (security_invoker = false)
AS
SELECT DISTINCT ON (t.charger_id, t.connector_id)
    t.site_id,
    t.charger_id,
    ch.code                 AS charger_code,
    t.connector_id,
    t.measured_at,
    t.status,
    t.power_w,
    t.energy_kwh,
    t.current_a,
    t.session_id,
    t.error_code,
    now() - t.measured_at   AS data_age
FROM ems.telemetry_ev_charger t
JOIN ems.asset_ev_charger ch ON ch.id = t.charger_id
ORDER BY t.charger_id, t.connector_id, t.measured_at DESC;

COMMENT ON VIEW ems.vw_latest_ev_charger IS
'Nejnovější telemetrická data pro každý konektor EV nabíječky. Slouží pro dashboard a řízení nabíjení.';

-- ------------------------------------------------------------

CREATE OR REPLACE VIEW ems.vw_latest_heat_pump
WITH (security_invoker = false)
AS
SELECT DISTINCT ON (t.heat_pump_id)
    t.site_id,
    t.heat_pump_id,
    hp.code                 AS heat_pump_code,
    t.measured_at,
    t.outdoor_temp_c,
    t.tuv_tank_temp_c,
    t.water_outlet_temp_c,
    t.power_w,
    t.operating_mode,
    t.cop_actual,
    t.defrost_active,
    t.alarm_code,
    -- Odhadovaný COP pro aktuální venkovní teplotu
    ems.fn_cop_estimate(t.heat_pump_id, t.outdoor_temp_c) AS cop_estimated,
    now() - t.measured_at   AS data_age
FROM ems.telemetry_heat_pump t
JOIN ems.asset_heat_pump hp ON hp.id = t.heat_pump_id
ORDER BY t.heat_pump_id, t.measured_at DESC;

COMMENT ON VIEW ems.vw_latest_heat_pump IS
'Nejnovější telemetrická data pro každé tepelné čerpadlo včetně odhadovaného COP.
Slouží pro real-time dashboard a rozhodovací logiku plánování.';
