-- =====================================================================================
-- RPC: rpc_admin_kefu_account_list
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取客服账号列表
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_account_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_accounts ka
    JOIN public.ak_users u ON u.id = ka.user_id
    WHERE (p_status IS NULL OR ka.status = p_status)
      AND (p_search IS NULL OR ka.nickname ILIKE '%' || p_search || '%' OR u.username ILIKE '%' || p_search || '%');

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

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