-- neúspěšný běh plánovače bez aktivace a bez supersede aktivního plánu

create or replace function ems.fn_planning_run_fail(
  p_site_id int,
  p_horizon_start timestamptz,
  p_horizon_end timestamptz,
  p_run_meta jsonb
)
returns int
language plpgsql
as $fn$
declare
  v_run_id int;
begin
  insert into ems.planning_run (
    site_id, horizon_start, horizon_end, status,
    run_type, triggered_by, replan_from,
    soc_at_replan_wh, solver_duration_ms, forecast_correction_factor,
    solver_params, error_text
  ) values (
    p_site_id,
    p_horizon_start,
    p_horizon_end,
    'failed',
    nullif(trim(p_run_meta->>'run_type'), ''),
    nullif(trim(p_run_meta->>'triggered_by'), ''),
    case
      when p_run_meta ? 'replan_from' and (p_run_meta->>'replan_from') is not null
        and (p_run_meta->>'replan_from') <> 'null'
      then (p_run_meta->>'replan_from')::timestamptz
      else null::timestamptz
    end,
    (p_run_meta->>'soc_at_replan_wh')::numeric,
    coalesce((p_run_meta->>'solver_duration_ms')::int, 0),
    coalesce((p_run_meta->>'forecast_correction_factor')::numeric, 1.0),
    case
      when p_run_meta ? 'solver_params' and jsonb_typeof(p_run_meta->'solver_params') = 'object'
      then p_run_meta->'solver_params'
      else null::jsonb
    end,
    nullif(trim(p_run_meta->>'error_text'), '')
  )
  returning id into v_run_id;

  return v_run_id;
end;
$fn$;

comment on function ems.fn_planning_run_fail is
  'Uloží planning_run se statusem failed; neaktivuje plán a nesupersededuje active.';
