-- =====================================================================================
-- Admin 系统功能 - 获取配置项 RPC
-- 位置：docs/sql/30_rpc/admin/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 依赖：ml_system_configs, ak_users 表已存在
-- =====================================================================================

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

    -- 2. 获取配置值
    SELECT config_value INTO v_value
    FROM public.ml_system_configs
    WHERE config_key = p_key;

    RETURN v_value;
END;
$$;