-- =====================================================================================
-- RPC: rpc_admin_kefu_feedback_process
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端处理用户留言反馈（回复内容并更新状态）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_feedback_process(
    p_id UUID,
    p_reply_content TEXT
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_ok BOOLEAN;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 更新状态
    UPDATE public.ml_kefu_feedbacks
    SET 
        status = 1, -- 已处理
        reply_content = p_reply_content,
        processed_at = now(),
        updated_at = now()
    WHERE id = p_id;

    GET DIAGNOSTICS v_ok = ROW_COUNT;
    RETURN v_ok;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_feedback_process IS '管理员处理并回复用户留言反馈';
