-- =====================================================================================
-- 8. 修复聊天消息表 (ml_chat_messages) 的 RLS 策略
-- 解决 403 Forbidden 问题 (无法发送消息) 和无法获取聊天记录的问题
-- 说明：supabaseService 发送的是 auth.uid()，所以 sender_id/receiver_id 存储的是 Auth ID
-- =====================================================================================

-- 1. 确保表存在 (如果尚未创建)
CREATE TABLE IF NOT EXISTS public.ml_chat_messages (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    sender_id UUID NOT NULL,   -- 发送方 Auth ID
    receiver_id UUID NOT NULL, -- 接收方 Auth ID (或店铺关联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 "chat_messages_update_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() = sender_id
    );

-- 策略：允许用户查询消息 (只要自己是 sender_id 或 receiver_id)
-- 注意：如果 receiver_id 是店铺ID，商家查询时可能需要额外逻辑 (此处仅保证作为 User 能看到自己的收发)
CREATE POLICY "chat_messages_select_policy" ON public.ml_chat_messages
    FOR SELECT USING (
        auth.uid() = sender_id 
        OR 
        auth.uid() = receiver_id
    );

-- 策略：允许用户更新消息 (仅限接收者标记已读)
CREATE POLICY "chat_messages_update_policy" ON public.ml_chat_messages
    FOR UPDATE USING (
        auth.uid() = receiver_id
    )
    WITH CHECK (
        auth.uid() = receiver_id
    );

-- =====================================================================================
-- 5. 补充索引
-- =====================================================================================
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);
