-- RPC: rpc_admin_delete_division
-- 管理端删除事业部（支持级联软删除关联代理）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_division(
  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:division:delete') THEN
    RAISE EXCEPTION 'Permission denied: distribution:division: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_agents
  SET deleted_at = now(),
      deleted_by = v_user_id
  WHERE division_uid = p_uid AND deleted_at IS NULL;

  -- 4. 级联软删除：该事业部的所有申请记录
  UPDATE public.ak_distribution_division_applications
  SET deleted_at = now(),
      deleted_by = v_user_id
  WHERE user_id = p_uid AND deleted_at IS NULL;

  -- 5. 软删除事业部本身
  UPDATE public.ak_distribution_divisions
  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_division(uuid) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_delete_division(uuid) TO authenticated;
