DROP FUNCTION IF EXISTS ems.fn_telemetry_inverter_sample;

CREATE OR REPLACE FUNCTION ems.fn_telemetry_inverter_sample(
  p_site_id int,
  p_inverter_id int,
  p_measured_at timestamptz,
  p_pv_power_w int,
  p_pv1_power_w int,
  p_pv2_power_w int,
  p_gen_port_power_w int,
  p_battery_soc_percent double precision,
  p_battery_power_w int,
  p_batt_charge_today_wh int,
  p_batt_discharge_today_wh int,
  p_grid_power_w int,
  p_load_power_w int,
  p_grid_import_total_wh bigint,
  p_grid_export_total_wh bigint,
  p_run_state int,
  p_is_export_limited boolean DEFAULT NULL,
  p_pv_derating_flags int DEFAULT NULL
)
RETURNS void
LANGUAGE sql
AS $fn$
  INSERT INTO ems.telemetry_inverter (
    site_id,
    inverter_id,
    measured_at,
    pv_power_w,
    pv1_power_w,
    pv2_power_w,
    gen_port_power_w,
    battery_soc_percent,
    battery_power_w,
    batt_charge_today_wh,
    batt_discharge_today_wh,
    grid_power_w,
    load_power_w,
    grid_import_total_wh,
    grid_export_total_wh,
    run_state,
    is_export_limited,
    pv_derating_flags
  )
  VALUES (
    p_site_id,
    p_inverter_id,
    p_measured_at,
    p_pv_power_w,
    p_pv1_power_w,
    p_pv2_power_w,
    p_gen_port_power_w,
    p_battery_soc_percent,
    p_battery_power_w,
    p_batt_charge_today_wh,
    p_batt_discharge_today_wh,
    p_grid_power_w,
    p_load_power_w,
    p_grid_import_total_wh,
    p_grid_export_total_wh,
    p_run_state,
    p_is_export_limited,
    p_pv_derating_flags
  )
  ON CONFLICT (inverter_id, measured_at) DO NOTHING;
$fn$;

COMMENT ON FUNCTION ems.fn_telemetry_inverter_sample IS
  'Insert jednoho vzorku telemetrie střídače (telemetry_collector). Volitelně is_export_limited / pv_derating_flags (Deye reg 145/179) pro vyloučení slotů z učení PV delty.';
