-- aktivní planning_run pro site (rolling horizon)

create or replace function ems.fn_planning_active_run(p_site_id int)
returns jsonb
language sql
stable
as $fn$
  select case
    when not exists (select 1 from ems.site s where s.id = p_site_id) then
      jsonb_build_object('error', 'unknown_site')
    when not exists (
      select 1 from ems.planning_run pr
      where pr.site_id = p_site_id and pr.status = 'active'
    ) then
      jsonb_build_object('error', 'no_active_plan')
    else (
      select jsonb_build_object(
        'id', pr.id,
        'horizon_end', pr.horizon_end,
        'horizon_start', pr.horizon_start,
        'created_at', pr.created_at
      )
      from ems.planning_run pr
      where pr.site_id = p_site_id and pr.status = 'active'
      order by pr.created_at desc
      limit 1
    )
  end;
$fn$;
