-- doplní chybějící audit_interval za posledních p_hours hodin (15min sloty)

create or replace function ems.fn_fill_audit_for_site_window(
  p_site_id int,
  p_hours int default 6
)
returns int
language plpgsql
as $fn$
declare
  v_last timestamptz;
  v_slot timestamptz;
  v_cnt int := 0;
begin
  v_last := date_trunc('minute', now())
    - (extract(minute from now())::int % 15) * interval '1 minute';
  v_last := v_last - interval '15 minutes';

  for v_slot in
    select gs.slot
    from generate_series(
      v_last - make_interval(hours => p_hours),
      v_last,
      interval '15 minutes'
    ) as gs(slot)
    where not exists (
      select 1 from ems.audit_interval ai
      where ai.site_id = p_site_id
        and ai.interval_start = gs.slot
    )
  loop
    perform ems.fn_fill_audit_interval(p_site_id, v_slot);
    perform ems.fn_fill_baseline_load_forecast_accuracy(p_site_id, v_slot);
    v_cnt := v_cnt + 1;
  end loop;

  return v_cnt;
end;
$fn$;
