-- =====================================================================================
-- 8. 修复聊天消息表 (ml_chat_messages) 的 RLS 策略
-- 解决 403 Forbidden 问题 (无法发送消息) 和无法获取聊天记录的问题
-- =====================================================================================

-- 1. 确保表存在 (如果尚未创建)
CREATE TABLE IF NOT EXISTS public.ml_chat_messages (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    sender_id UUID NOT NULL,   -- 发送方ID (关联 ak_users.id)
    receiver_id UUID NOT NULL, -- 接收方ID (关联 ak_users.id)
    content TEXT NOT NULL,
    msg_type VARCHAR(20) DEFAULT 'text', -- text, image, etc
    is_read BOOLEAN DEFAULT FALSE,
    is_from_user BOOLEAN DEFAULT TRUE,
    extra_data TEXT,           -- 额外JSON数据
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 2. 开启 RLS
ALTER TABLE public.ml_chat_messages ENABLE ROW LEVEL SECURITY;

-- 3. 清理旧策略 (避免冲突)
DROP POLICY IF EXISTS "Chat messages insert policy" ON public.ml_chat_messages;
DROP POLICY IF EXISTS "Chat messages select policy" ON public.ml_chat_messages;
DROP POLICY IF EXISTS "Users can insert their own messages" ON public.ml_chat_messages;
DROP POLICY IF EXISTS "Users can view their own messages" ON public.ml_chat_messages;
DROP POLICY IF EXISTS "chat_insert_policy" ON public.ml_chat_messages;
DROP POLICY IF EXISTS "chat_select_policy" ON public.ml_chat_messages;

-- 4. 创建新策略

-- 策略：允许用户插入消息 (只要 sender_id 是自己)
CREATE POLICY "chat_messages_insert_policy" ON public.ml_chat_messages
    FOR INSERT WITH CHECK (
        -- 检查当前登录用户 (auth.uid()) 对应的 ak_users.id 是否等于要插入的 sender_id
        EXISTS (
            SELECT 1 FROM public.ak_users
            WHERE auth_id = auth.uid()
            AND id = sender_id
        )
    );

-- 策略：允许用户查询消息 (只要自己是 sender_id 或 receiver_id)
CREATE POLICY "chat_messages_select_policy" ON public.ml_chat_messages
    FOR SELECT USING (
        -- 检查当前登录用户是否是发送者或接收者
        EXISTS (
            SELECT 1 FROM public.ak_users
            WHERE auth_id = auth.uid()
            AND (id = sender_id OR id = receiver_id)
        )
    );

-- 策略：允许用户更新消息 (仅限标记已读，且自己是接收者)
CREATE POLICY "chat_messages_update_policy" ON public.ml_chat_messages
    FOR UPDATE USING (
        EXISTS (
            SELECT 1 FROM public.ak_users
            WHERE auth_id = auth.uid()
            AND id = receiver_id
        )
    )
    WITH CHECK (
        EXISTS (
            SELECT 1 FROM public.ak_users
            WHERE auth_id = auth.uid()
            AND id = receiver_id
        )
    );

-- =====================================================================================
-- 补充：确保 ak_users 上有适当的索引以提高 RLS 性能
-- =====================================================================================
CREATE INDEX IF NOT EXISTS idx_ak_users_auth_id ON public.ak_users(auth_id);
CREATE INDEX IF NOT EXISTS idx_chat_messages_sender ON public.ml_chat_messages(sender_id);
CREATE INDEX IF NOT EXISTS idx_chat_messages_receiver ON public.ml_chat_messages(receiver_id);
CREATE INDEX IF NOT EXISTS idx_chat_messages_created_at ON public.ml_chat_messages(created_at DESC);
