-- ============================================================================
-- Add sender_device_id to messages so receivers know which device's public
-- key to verify against when decrypting an envelope.
-- ============================================================================

alter table public.messages
  add column if not exists sender_device_id uuid references public.devices(id) on delete set null;

create index if not exists messages_sender_device_idx on public.messages(sender_device_id);

-- Tighten the insert policy: sender_device_id (when set) must belong to the caller.
drop policy if exists messages_insert_member on public.messages;
create policy messages_insert_member on public.messages
  for insert to authenticated
  with check (
    sender_id = auth.uid()
    and public.is_conversation_member(conversation_id)
    and (
      sender_device_id is null
      or exists (
        select 1 from public.devices d
         where d.id = sender_device_id and d.user_id = auth.uid()
      )
    )
  );
