async def exchange_white_label_oauth2_code(
    *,
    request: Request,
    response: Response,
    white_label_id: UUID,
    code: str = Body(...),
    source_connection_in: Optional[schemas.SourceConnectionCreate] = Body(None),
    db: AsyncSession = Depends(deps.get_db),
    user: User = Depends(deps.get_user),
    background_tasks: BackgroundTasks,
) -> schemas.SourceConnection:
    """Exchange OAuth2 code for tokens and create connection with source connection.

    Args:
    -----
        request: The HTTP request
        response: The HTTP response
        white_label_id: The ID of the white label to exchange the code for
        code: The OAuth2 code
        source_connection_in: Optional source connection configuration
        db: The database session
        user: The current user
        background_tasks: Background tasks for async operations

    Returns:
    --------
        source_connection (schemas.SourceConnection): The created source connection
    """
    # Handle CORS for white label
    await _handle_white_label_cors(request, response, white_label_id, db, user)

    # Handle OPTIONS request for preflight
    if request.method == "OPTIONS":
        return ""

    white_label = await crud.white_label.get(db, id=white_label_id, current_user=user)
    if not white_label:
        raise HTTPException(status_code=404, detail="White label integration not found")
    if white_label.organization_id != user.organization_id:
        raise HTTPException(status_code=403, detail="Not enough permissions")

    white_label = schemas.WhiteLabel.model_validate(white_label, from_attributes=True)

    try:
        # Exchange code for connection
        connection = await oauth2_service.create_oauth2_connection_for_whitelabel(
            db=db, white_label=white_label, code=code, user=user
        )

        # Create or use the provided source connection config
        if source_connection_in is None:
            # If no source connection provided, create one with defaults
            source_connection_in = schemas.SourceConnectionCreate(
                name=f"{connection.name} from {white_label.name}",
                description=f"Created from white label {white_label.name}",
                short_name=white_label.source_short_name,
                sync_immediately=True,
                white_label_id=white_label_id,
                credential_id=connection.integration_credential_id,
            )
        else:
            # Ensure white_label_id and short_name are set correctly
            source_connection_in.white_label_id = white_label_id
            if not source_connection_in.short_name:
                source_connection_in.short_name = white_label.source_short_name

        # Create the source connection with the connection ID
        source_connection, sync_job = await source_connection_service.create_source_connection(
            db=db,
            source_connection_in=source_connection_in,
            current_user=user,
        )

        # If job was created and sync_immediately is True, start it in background
        if sync_job:
            async with get_db_context() as sync_db:
                sync_dag = await sync_service.get_sync_dag(
                    db=sync_db, sync_id=source_connection.sync_id, current_user=user
                )

                # Get the sync object
                sync = await crud.sync.get(
                    db=sync_db, id=source_connection.sync_id, current_user=user
                )
                sync = schemas.Sync.model_validate(sync, from_attributes=True)
                sync_job = schemas.SyncJob.model_validate(sync_job, from_attributes=True)
                sync_dag = schemas.SyncDag.model_validate(sync_dag, from_attributes=True)
                collection = await crud.collection.get_by_readable_id(
                    db=sync_db, readable_id=source_connection.collection, current_user=user
                )
                collection = schemas.Collection.model_validate(collection, from_attributes=True)

            background_tasks.add_task(
                sync_service.run, sync, sync_job, sync_dag, collection, source_connection, user
            )

        # Make sure we are returning the source_connection, not anything else
        logger.debug(f"Returning source_connection: {source_connection}")
        return source_connection

    except Exception as e:
        logger.error(f"Failed to exchange OAuth2 code for WhiteLabel {white_label.id}: {e}")
        # Pass through the detailed error message if it's an HTTPException
        if isinstance(e, HTTPException):
            raise
        raise HTTPException(status_code=400, detail=str(e)) from e
Exchange OAuth2 code for tokens and create connection with source connection.

    Args:
    -----
        request: The HTTP request
        response: The HTTP response
        white_label_id: The ID of the white label to exchange the code for
        code: The OAuth2 code
        source_connection_in: Optional source connection configuration
        db: The database session
        user: The current user
        background_tasks: Background tasks for async operations

    Returns:
    --------
        source_connection (schemas.SourceConnection): The created source connection
    
backend/airweave/api/v1/endpoints/white_label.py