-- RLS Policies

ALTER TABLE users ENABLE ROW LEVEL SECURITY;

ALTER TABLE message_threads ENABLE ROW LEVEL SECURITY;

ALTER TABLE thread_participants ENABLE ROW LEVEL SECURITY;

ALTER TABLE messages ENABLE ROW LEVEL SECURITY;


-- Users policies

CREATE
POLICY "Users can view their own profile"

  ON users FOR
SELECT
    USING (auth.uid() = uuid);



CREATE
POLICY "Users can view indexable profiles"

  ON users FOR
SELECT
    USING (indexable = true);



CREATE
POLICY "Users can update their own profile"

  ON users FOR
UPDATE
    USING (auth.uid() = uuid);


-- Message threads policies

CREATE
POLICY "Users can view their threads"

  ON message_threads FOR
SELECT
    USING (is_thread_participant(id));


-- Thread participants policies

CREATE
POLICY "Users can view their thread participants"

  ON thread_participants FOR
SELECT
    USING (is_thread_participant(thread_id));


-- Messages policies

CREATE
POLICY "Users can view their messages"

  ON messages FOR
SELECT
    USING (is_thread_participant(thread_id));



CREATE
POLICY "Users can send messages"

  ON messages FOR INSERT

  WITH CHECK (is_thread_participant(thread_id));