-- Bulk reassign team_member_id on a list of entries, in one UPDATE.
-- Mirrors restamp_billout_for_entry_ids but changes WHICH member the
-- entries are billed for (not just re-applying current rates).
--
-- Stamps:
--   - team_member_id      → the picked member
--   - converted_user       → consolidate_as ?? display_name (cached)
--   - converted_duration_seconds → source × rate_proportion (Toggl export legacy)
--
-- Does NOT re-stamp billout_cost_usd / billout_amount_usd — call
-- restamp_billout_for_entry_ids right after, since cost + billout
-- depend on cost_rate / billout_rate / project overrides for the NEW
-- member. The two-step is intentional: this function only touches
-- identity columns so its scope is auditable.
--
-- Returns the number of rows updated.

create or replace function public.set_team_member_for_entry_ids(
  p_org_id uuid,
  p_team_member_id uuid,
  p_entry_ids uuid[]
)
returns bigint
language sql
volatile
security invoker
set search_path = public
as $$
  with member as (
    select id, display_name, consolidate_as, rate_proportion
    from public.team_members
    where id = p_team_member_id and org_id = p_org_id
  ),
  updated as (
    update public.time_entries te
    set
      team_member_id = m.id,
      converted_user = coalesce(m.consolidate_as, m.display_name),
      converted_duration_seconds = case
        when te.duration_seconds is null then null
        else round(te.duration_seconds * m.rate_proportion)::bigint
      end
    from member m
    where te.org_id = p_org_id
      and te.id = any (p_entry_ids)
    returning te.id
  )
  select coalesce(count(*), 0)::bigint from updated
$$;

comment on function public.set_team_member_for_entry_ids(uuid, uuid, uuid[]) is
  'Bulk-reassign team_member_id on a list of entries. Stamps team_member_id, converted_user, converted_duration_seconds. Caller MUST follow up with restamp_billout_for_entry_ids to refresh cost + billout. Returns rows updated.';
