create or replace function ems.fn_ote_list_missing_days(p_from date, p_to date)
returns table(day_local date)
language sql
stable
as $fn$
  with days as (
    select gs::date as d
    from generate_series(p_from::timestamp, p_to::timestamp, interval '1 day') gs
  ),
  counts as (
    select
      (mip.interval_start at time zone 'Europe/Prague')::date as d,
      count(*)::int as n
    from ems.market_interval_price mip
    where mip.market_source = 'OTE_CZ'
      and (mip.interval_start at time zone 'Europe/Prague')::date between p_from and p_to
    group by 1
  )
  select days.d as day_local
  from days
  left join counts c on c.d = days.d
  where coalesce(c.n, 0) not in (92, 96, 100);
$fn$;

comment on function ems.fn_ote_list_missing_days(date, date) is
  'Kalendářní dny v rozsahu bez „plného“ počtu OTE slotů (backfill).';
