-- Single-query re-stamp of billout_amount_usd for every entry on a
-- project (optionally narrowed to one team_member). Used by the override
-- upsert/delete actions to recompute the per-entry cache after a rule
-- change. Replaces the previous N-round-trip loop that was ~10 seconds
-- for a 1000-row project.

create or replace function public.restamp_billout_for_project(
  p_org_id uuid,
  p_project_id uuid,
  p_team_member_id uuid default null
)
returns bigint
language sql
volatile
security invoker
set search_path = public
as $$
  with updated as (
    update public.time_entries te
    set billout_amount_usd = case
      when te.converted_duration_seconds is null then null
      else round(
        (te.converted_duration_seconds::numeric / 3600)
        * coalesce(
            public.effective_billout_rate(te.team_member_id, te.project_id),
            0
          )
        * 100
      ) / 100
    end
    where te.org_id = p_org_id
      and te.project_id = p_project_id
      and (p_team_member_id is null or te.team_member_id = p_team_member_id)
      and te.converted_duration_seconds is not null
    returning 1
  )
  select coalesce(count(*), 0)::bigint from updated
$$;

comment on function public.restamp_billout_for_project is
  'Re-compute billout_amount_usd for every entry on the given project (optionally only for one team_member). Used by override rule changes. Returns the count of rows updated.';
