-- Jedno volání DB pro GET /plan/compare (aktivní bundle + comparison run debug).

create or replace function ems.fn_plan_compare_bundle(p_site_id int)
returns jsonb
language plpgsql
stable
as $fn$
declare
  v_active jsonb;
  v_active_run_id int;
  v_compare_run_id int;
  v_comparison jsonb;
begin
  v_active := ems.fn_plan_current_bundle(p_site_id);
  if v_active ? 'error' then
    return v_active;
  end if;

  v_active_run_id := (v_active->'run'->>'id')::int;
  if v_active_run_id is null then
    return jsonb_build_object('error', 'no_active_plan');
  end if;

  select pr.id
  into v_compare_run_id
  from ems.planning_run pr
  where pr.site_id = p_site_id
    and pr.status = 'comparison'
    and (pr.solver_params->>'comparison_of_run_id')::int = v_active_run_id
  order by pr.created_at desc
  limit 1;

  if v_compare_run_id is null then
    select pr.id
    into v_compare_run_id
    from ems.planning_run pr
    where pr.site_id = p_site_id
      and pr.status = 'comparison'
    order by pr.created_at desc
    limit 1;
  end if;

  if v_compare_run_id is null then
    return jsonb_build_object('error', 'no_comparison_plan');
  end if;

  v_comparison := ems.fn_planning_run_debug(v_compare_run_id);
  if v_comparison is null then
    return jsonb_build_object('error', 'no_comparison_plan');
  end if;

  return jsonb_build_object(
    'active', v_active,
    'comparison', v_comparison
  );
end;
$fn$;

comment on function ems.fn_plan_compare_bundle(int) is
  'Aktivní plán + comparison planning_run (GET /plan/compare).';
