-- RPC: rpc_admin_get_diy_page_list
-- 管理端获取 DIY 页面分页列表
-- 支持按名称搜索和按类型筛选

CREATE OR REPLACE FUNCTION public.rpc_admin_get_diy_page_list(
  p_search text DEFAULT NULL,
  p_type text DEFAULT NULL,
  p_page integer DEFAULT 1,
  p_page_size integer DEFAULT 20
)
RETURNS JSONB
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_page integer := GREATEST(1, COALESCE(p_page, 1));
  v_page_size integer := LEAST(200, GREATEST(1, COALESCE(p_page_size, 20)));
  v_offset integer := (v_page - 1) * v_page_size;
  v_total bigint;
  v_items jsonb;
BEGIN
  -- 1. 权限检查 (仅管理员或分析员)
  IF NOT EXISTS (
    SELECT 1 FROM public.ak_users u
    WHERE u.id = auth.uid() AND u.role IN ('admin', 'analytics')
  ) THEN
    RAISE EXCEPTION 'permission denied';
  END IF;

  -- 2. 获取总数
  SELECT COUNT(*) INTO v_total
  FROM public.ak_diy_pages
  WHERE (p_search IS NULL OR p_search = '' OR name ILIKE '%' || p_search || '%')
    AND (p_type IS NULL OR type = p_type);

  -- 3. 获取明细
  SELECT jsonb_agg(t) INTO v_items
  FROM (
    SELECT 
      id, name, type, is_home, is_active, 
      created_at, updated_at
    FROM public.ak_diy_pages
    WHERE (p_search IS NULL OR p_search = '' OR name ILIKE '%' || p_search || '%')
      AND (p_type IS NULL OR type = p_type)
    ORDER BY created_at DESC
    LIMIT v_page_size OFFSET v_offset
  ) t;

  -- 4. 返回 JSON 结果
  RETURN jsonb_build_object(
    'total', v_total,
    'items', COALESCE(v_items, '[]'::jsonb)
  );
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_diy_page_list(text, text, integer, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_diy_page_list(text, text, integer, integer) TO authenticated;
