-- =====================================================================================
-- 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_save(
    p_key TEXT,
    p_value JSONB,
    p_description TEXT DEFAULT NULL
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
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. 插入或更新配置
    INSERT INTO public.ml_system_configs (config_key, config_value, description, updated_at)
    VALUES (p_key, p_value, p_description, NOW())
    ON CONFLICT (config_key) DO UPDATE
    SET 
        config_value = EXCLUDED.config_value,
        description = COALESCE(EXCLUDED.description, public.ml_system_configs.description),
        updated_at = NOW();

    RETURN TRUE;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_system_config_save(TEXT, JSONB, TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_system_config_save(TEXT, JSONB, TEXT) TO authenticated;
