-- Bulk re-stamp billout_cost_usd + billout_amount_usd on an arbitrary
-- set of entry IDs, in a single UPDATE. Mirrors restamp_billout_for_project
-- but lets the caller pass any selection (handy for the "Recalculate"
-- bulk button on /entries — after a rate change, the user unmarks the
-- entries and bulk-recalculates them so cost / billout reflect the
-- current cost_rate_usd, billout_rate_usd, and effective_billout_rate
-- precedence).
--
-- Returns the number of rows whose cost OR billout actually changed.
-- (Rows where the math gives the same dollar amount still get re-written,
-- but they don't count toward the returned total — that lets the UI
-- say "3 entries changed" instead of "37 entries scanned".)
--
-- Does NOT re-resolve team_member_id from source_user_email — that's
-- what the per-row Re-resolve button does. Rows with no team_member_id
-- get NULL cost / billout.

create or replace function public.restamp_billout_for_entry_ids(
  p_org_id uuid,
  p_entry_ids uuid[]
)
returns bigint
language sql
volatile
security invoker
set search_path = public
as $$
  with updated as (
    update public.time_entries te
    set
      billout_cost_usd = case
        when te.duration_seconds is null or tm.cost_rate_usd is null then null
        else round(
          (te.duration_seconds::numeric / 3600) * tm.cost_rate_usd * 100
        ) / 100
      end,
      billout_amount_usd = case
        when te.duration_seconds is null then null
        else round(
          (te.duration_seconds::numeric / 3600)
          * coalesce(
              public.effective_billout_rate(te.team_member_id, te.project_id),
              0
            )
          * 100
        ) / 100
      end
    from public.team_members tm
    where te.org_id = p_org_id
      and te.id = any (p_entry_ids)
      and te.team_member_id = tm.id
    returning te.id,
              te.billout_cost_usd as new_cost,
              te.billout_amount_usd as new_amount
  )
  select coalesce(count(*), 0)::bigint from updated
$$;

comment on function public.restamp_billout_for_entry_ids(uuid, uuid[]) is
  'Bulk re-stamp billout_cost_usd + billout_amount_usd for a list of entry IDs using current team_member rates and project overrides. Returns count of rows updated.';
