-- RPC: rpc_admin_get_permission_list
-- 管理端获取全量权限/菜单列表 (供前端构建树形结构)

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

    -- 2. 获取全量数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            id, parent_id, name, code, type, 
            path, icon, sort_order, is_visible,
            created_at, updated_at
        FROM public.ak_permissions
        WHERE deleted_at IS NULL
        ORDER BY sort_order ASC, created_at ASC
    ) t;

    RETURN COALESCE(v_items, '[]'::jsonb);
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_permission_list() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_permission_list() TO authenticated;
