-- =============================================================
-- R__056_vw_energy_flows.sql
-- Denní agregace 6 základních Wh + 7 směrových toků z audit_interval
-- Repeatable migration (závisí na audit_interval + V042 sloupcech)
-- =============================================================

DROP VIEW IF EXISTS ems.vw_energy_flows_daily CASCADE;

CREATE VIEW ems.vw_energy_flows_daily AS
SELECT
    site_id,
    (date_trunc('day', interval_start AT TIME ZONE 'Europe/Prague'))::date AS day_local,
    ROUND(SUM(COALESCE(actual_pv_production_wh, 0)) / 1000, 3)       AS pv_production_kwh,
    ROUND(SUM(ems.fn_audit_grid_import_wh_for_economics(
          actual_grid_import_wh, actual_grid_export_wh, actual_grid_power_w)) / 1000, 3) AS grid_import_kwh,
    ROUND(SUM(ems.fn_audit_grid_export_wh_for_economics(
          actual_grid_import_wh, actual_grid_export_wh, actual_grid_power_w)) / 1000, 3) AS grid_export_kwh,
    ROUND(SUM(COALESCE(actual_batt_charge_wh, 0)) / 1000, 3)          AS batt_charge_kwh,
    ROUND(SUM(COALESCE(actual_batt_discharge_wh, 0)) / 1000, 3)     AS batt_discharge_kwh,
    ROUND(SUM(COALESCE(actual_load_consumption_wh, 0)) / 1000, 3)   AS load_kwh,
    ROUND(SUM(COALESCE(flow_pv_to_load_wh, 0)) / 1000, 3)           AS pv_to_load_kwh,
    ROUND(SUM(COALESCE(flow_pv_to_batt_wh, 0)) / 1000, 3)           AS pv_to_batt_kwh,
    ROUND(SUM(COALESCE(flow_pv_to_grid_wh, 0)) / 1000, 3)           AS pv_to_grid_kwh,
    ROUND(SUM(COALESCE(flow_batt_to_load_wh, 0)) / 1000, 3)         AS batt_to_load_kwh,
    ROUND(SUM(COALESCE(flow_batt_to_grid_wh, 0)) / 1000, 3)         AS batt_to_grid_kwh,
    ROUND(SUM(COALESCE(flow_grid_to_load_wh, 0)) / 1000, 3)        AS grid_to_load_kwh,
    ROUND(SUM(COALESCE(flow_grid_to_batt_wh, 0)) / 1000, 3)         AS grid_to_batt_kwh
FROM ems.audit_interval
GROUP BY
    site_id,
    (date_trunc('day', interval_start AT TIME ZONE 'Europe/Prague'))::date;

COMMENT ON VIEW ems.vw_energy_flows_daily IS
'Denní součty energie a toků (prioritní alokace z fn_fill_audit_interval). PV/baterie/load/flow z Wh sloupců;
grid import/export kWh používají fn_audit_grid_*_wh_for_economics – shodně jako audit po doplnění intervalu.';
