-- ============================================================================
-- Allow the sender of a message to SELECT all its envelopes (needed so
-- ON CONFLICT UPDATE during message edit can detect the existing rows).
-- The existing envelopes_select_own_device policy only lets a device owner
-- read envelopes targeted at their own device, which is why sender-driven
-- upsert was failing for envelopes aimed at other users' devices.
-- ============================================================================

create policy envelopes_select_sender on public.message_envelopes
  for select to authenticated
  using (
    exists (
      select 1 from public.messages m
      where m.id = message_id and m.sender_id = auth.uid()
    )
  );
