-- This snippet updates the policy to allow the sender of messages and participants in the thread to receive realtime events.

-- First, let's drop the existing policy

DROP
POLICY IF EXISTS "Thread participants access" ON public.messages;



-- 1. First ensure RLS is enabled

ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;


-- 2. Set REPLICA IDENTITY to FULL (required for realtime)

ALTER TABLE public.messages REPLICA IDENTITY FULL;


-- Check current publication configuration

SELECT *

FROM pg_publication_tables

WHERE pubname = 'supabase_realtime';


-- Just set these then:

ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;



ALTER TABLE public.messages REPLICA IDENTITY FULL;



GRANT
    SELECT

    ,
    INSERT ON public.messages TO authenticated;



GRANT
USAGE
ON
SCHEMA
public TO authenticated;



CREATE
POLICY "Thread participants access" ON public.messages FOR ALL USING (

  auth.uid () IN (

    SELECT

      user_uuid

    FROM

      thread_participants

    WHERE

      thread_id = messages.thread_id

  )

);

