-- =====================================================================================
-- RPC: rpc_admin_kefu_feedback_list
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取用户留言反馈列表
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_feedback_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_search TEXT DEFAULT NULL,
    p_status SMALLINT DEFAULT NULL
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_offset INTEGER;
    v_total BIGINT;
    v_items JSONB;
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;

    v_offset := (p_page - 1) * p_page_size;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ml_kefu_feedbacks f
    LEFT JOIN public.ak_users u ON u.id = f.user_id
    WHERE (p_status IS NULL OR f.status = p_status)
      AND (p_search IS NULL OR f.nickname ILIKE '%' || p_search || '%' OR f.phone ILIKE '%' || p_search || '%' OR f.content ILIKE '%' || p_search || '%');

    -- 3. 获取数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            f.id,
            f.user_id,
            f.nickname,
            f.phone,
            f.content,
            f.status,
            f.reply_content,
            f.processed_at,
            f.created_at,
            f.updated_at,
            u.username as user_account
        FROM public.ml_kefu_feedbacks f
        LEFT JOIN public.ak_users u ON u.id = f.user_id
        WHERE (p_status IS NULL OR f.status = p_status)
          AND (p_search IS NULL OR f.nickname ILIKE '%' || p_search || '%' OR f.phone ILIKE '%' || p_search || '%' OR f.content ILIKE '%' || p_search || '%')
        ORDER BY f.created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_feedback_list IS '管理员分页查询用户留言反馈列表';
