-- RPC: rpc_admin_save_diy_page
-- 管理端新增或更新 DIY 页面配置

CREATE OR REPLACE FUNCTION public.rpc_admin_save_diy_page(
  p_id uuid DEFAULT NULL,
  p_name text DEFAULT NULL,
  p_type text DEFAULT NULL,
  p_config jsonb DEFAULT '{}'::jsonb,
  p_is_active boolean DEFAULT true
)
RETURNS uuid
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_id uuid;
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. 新增或更新
  IF p_id IS NULL THEN
    INSERT INTO public.ak_diy_pages (
      name, type, config, is_active, updated_by, created_by
    ) VALUES (
      p_name, p_type, p_config, p_is_active, auth.uid(), auth.uid()
    ) RETURNING id INTO v_id;
  ELSE
    UPDATE public.ak_diy_pages
    SET
      name = COALESCE(p_name, name),
      type = COALESCE(p_type, type),
      config = COALESCE(p_config, config),
      is_active = COALESCE(p_is_active, is_active),
      updated_at = now(),
      updated_by = auth.uid()
    WHERE id = p_id
    RETURNING id INTO v_id;

    IF v_id IS NULL THEN
      RAISE EXCEPTION 'page not found';
    END IF;
  END IF;

  RETURN v_id;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_save_diy_page(uuid, text, text, jsonb, boolean) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_diy_page(uuid, text, text, jsonb, boolean) TO authenticated;
