-- RPC: rpc_admin_delete_agent
-- 管理端删除代理商（支持级联软删除代理申请记录）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_agent(
  p_uid 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('distribution:agent:delete') THEN
    RAISE EXCEPTION 'Permission denied: distribution:agent:delete';
  END IF;

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

  -- 3. 级联软删除：该代理的所有申请记录
  UPDATE public.ak_distribution_agent_applications
  SET deleted_at = now(),
      deleted_by = v_user_id
  WHERE user_id = p_uid AND deleted_at IS NULL;

  -- 4. 软删除代理商记录
  UPDATE public.ak_distribution_agents
  SET deleted_at = now(),
      deleted_by = v_user_id
  WHERE uid = p_uid AND deleted_at IS NULL;
  
  GET DIAGNOSTICS v_ok = ROW_COUNT;
  RETURN v_ok;
END;
$$;

REVOKE ALL ON FUNCTION public.rpc_admin_delete_agent(uuid) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_delete_agent(uuid) TO authenticated;
