-- Fix RLS policies for secure chat messages to ensure participants can access them.

-- 1. Ensure RLS is enabled on the encrypted_messages table.
ALTER TABLE public.encrypted_messages ENABLE ROW LEVEL SECURITY;

-- 2. Policy for SELECTing messages.
-- Allows a user to read messages in conversations they are a participant in.
DROP POLICY IF EXISTS "Allow participants to read messages" ON public.encrypted_messages;
CREATE POLICY "Allow participants to read messages"
ON public.encrypted_messages FOR SELECT USING (
  exists (
    select 1
    from public.encrypted_conversations
    where id = encrypted_messages.conversation_id
    and (
      participant_a = auth.uid() or
      participant_b = auth.uid()
    )
  )
);

-- 3. Policy for INSERTing new messages.
-- Allows a user to insert a message if they are the sender and a participant
-- in the conversation.
DROP POLICY IF EXISTS "Allow participants to send messages" ON public.encrypted_messages;
CREATE POLICY "Allow participants to send messages"
ON public.encrypted_messages FOR INSERT WITH CHECK (
  sender_id = auth.uid() AND
  exists (
    select 1
    from public.encrypted_conversations
    where id = encrypted_messages.conversation_id
    and (
      participant_a = auth.uid() or
      participant_b = auth.uid()
    )
  )
);

-- 4. Policy for UPDATing messages (e.g., marking as read).
-- Allows a participant to update a message in their conversation.
-- The client-side code should enforce that only the recipient can mark as read.
DROP POLICY IF EXISTS "Allow participants to update messages" ON public.encrypted_messages;
CREATE POLICY "Allow participants to update messages"
ON public.encrypted_messages FOR UPDATE USING (
  exists (
    select 1
    from public.encrypted_conversations
    where id = encrypted_messages.conversation_id
    and (
      participant_a = auth.uid() or
      participant_b = auth.uid()
    )
  )
) WITH CHECK (
  exists (
    select 1
    from public.encrypted_conversations
    where id = encrypted_messages.conversation_id
    and (
      participant_a = auth.uid() or
      participant_b = auth.uid()
    )
  )
);
