-- RPC: rpc_admin_set_home_page
-- 管理端设置生效首页
-- 逻辑：先取消所有同类型页面的 is_home 状态，再设置目标页面为 is_home

CREATE OR REPLACE FUNCTION public.rpc_admin_set_home_page(
  p_id uuid
)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_type text;
BEGIN
  -- 1. 权限检查 (仅管理员)
  IF NOT EXISTS (
    SELECT 1 FROM public.ak_users u
    WHERE u.id = auth.uid() AND u.role = 'admin'
  ) THEN
    RAISE EXCEPTION 'permission denied';
  END IF;

  -- 2. 获取目标页面类型
  SELECT type INTO v_type FROM public.ak_diy_pages WHERE id = p_id;
  IF v_type IS NULL THEN
    RAISE EXCEPTION 'page not found';
  END IF;

  -- 3. 原子切换：同一类型的页面只能有一个 is_home
  UPDATE public.ak_diy_pages SET is_home = false WHERE type = v_type;
  UPDATE public.ak_diy_pages SET is_home = true WHERE id = p_id;

  RETURN true;
END;
$$;

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