-- Enable RLS permissions for Chat Messages
-- Previously only SELECT was allowed, blocking USERS from sending messages (INSERT)

-- 1. Policy for INSERT (Sending messages)
-- User can insert if they are the sender (linked via ak_users)
DROP POLICY IF EXISTS ml_chat_messages_insert_policy ON public.ml_chat_messages;
CREATE POLICY ml_chat_messages_insert_policy ON public.ml_chat_messages
FOR INSERT WITH CHECK (
    auth.uid() IN (
        SELECT auth_id FROM public.ak_users WHERE id = sender_id
    )
);

-- 2. Policy for UPDATE (Marking as read)
-- Sender or Receiver can update (e.g. mark as read)
DROP POLICY IF EXISTS ml_chat_messages_update_policy ON public.ml_chat_messages;
CREATE POLICY ml_chat_messages_update_policy ON public.ml_chat_messages
FOR UPDATE USING (
    auth.uid() IN (
        SELECT auth_id FROM public.ak_users WHERE id IN (sender_id, receiver_id)
    )
);

-- 3. Ensure SELECT policy is also correct (existing one is complex, this is a simpler backup if needed)
-- (We trust the existing select policy if it exists, but making sure)
-- The existing policy:
-- auth.uid() IN (SELECT auth_id FROM ak_users WHERE id IN (sender_id, receiver_id))
