-- RPC: rpc_admin_delete_diy_page
-- 管理端删除 DIY 页面配置（支持权限检查与首页保护）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_diy_page(
  p_id uuid
)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_ok boolean;
  v_user_id UUID;
BEGIN
  -- 1. 权限检查 (使用通用权限校验函数)
  IF NOT public.check_admin_permission('decoration:page:delete') THEN
    RAISE EXCEPTION 'Permission denied: decoration:page:delete';
  END IF;

  -- 2. 获取当前操作用户 ID
  SELECT id INTO v_user_id FROM public.ak_users WHERE auth_id = auth.uid();

  -- 3. 校验：不允许删除当前生效的首页
  IF EXISTS (
    SELECT 1 FROM public.ak_diy_pages 
    WHERE id = p_id AND is_home = true AND deleted_at IS NULL
  ) THEN
    RAISE EXCEPTION 'cannot delete the active home page';
  END IF;

  -- 4. 执行软删除：标记 deleted_at
  UPDATE public.ak_diy_pages
  SET deleted_at = now(),
      deleted_by = v_user_id
  WHERE id = p_id AND deleted_at IS NULL;
  
  GET DIAGNOSTICS v_ok = ROW_COUNT;
  RETURN v_ok;
END;
$$;

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