Private/GDAP/New-GDAPRelationship.ps1

function New-GDAPRelationship {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$CustomerTenantId
    )

    try {
        $customer = Get-PartnerCustomer -CustomerTenantId $CustomerTenantId
        if (!$customer) {
            Write-ModuleLog "Customer with tenant ID $CustomerTenantId not found" -Level Error -Component 'GDAP' -ThrowError
        }

        # Create relationship request parameters
        $relationshipParams = @{
            displayName = "Jysk IT - $(New-Guid)"
            duration = "P730D"
            autoExtendDuration = "P180D"
            customer = @{
                tenantId = $CustomerTenantId
                displayName = $customer.companyProfile.companyName
            }
            accessDetails = $script:Config.GDAP.AccessDetails
        }

        # Connect to partner tenant
        Connect-CustomerGraph -CustomerTenantId $script:Config.PartnerTenantId -FlowType 'Delegated' -Force

        # Create the relationship
        Write-Host $relationshipParams
        $relationship = New-MgTenantRelationshipDelegatedAdminRelationship -BodyParameter $relationshipParams
        Write-ModuleLog -Message "Created new GDAP relationship: $($relationship.DisplayName)" -Level Info -Component 'GDAP'

        # Lock for approval
        New-MgTenantRelationshipDelegatedAdminRelationshipRequest `
            -DelegatedAdminRelationshipId $relationship.Id `
            -Action "LockForApproval" | Out-Null
        
        Write-ModuleLog -Message "Successfully locked relationship $($relationship.DisplayName) for approval" -Level Info -Component 'GDAP'

        return $relationship
    }
    catch {
        Write-ModuleLog -Message "Failed to create GDAP relationship: $($_.Exception.Message)" -Level Error -Component 'GDAP' -ErrorRecord $_ -ThrowError
    }
}

function Wait-GDAPApproval {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$RelationshipId,

        [Parameter()]
        [int]$TimeoutMinutes = 30
    )

    try {
        $timeout = (Get-Date).AddMinutes($TimeoutMinutes)
        
        while ((Get-Date) -lt $timeout) {
            $relationship = Get-MgTenantRelationshipDelegatedAdminRelationship -DelegatedAdminRelationshipId $RelationshipId
            
            if ($relationship.Status -eq "active") {
                Write-ModuleLog -Message "GDAP relationship is now active" -Level Info -Component 'GDAP'
                return $true
            }
            
            Write-ModuleLog -Message "Waiting for GDAP approval..." -Level Info -Component 'GDAP'
            Start-Sleep -Seconds 10
        }

        Write-ModuleLog -Message "Timeout waiting for GDAP approval" -Level Error -Component 'GDAP' -ThrowError
    }
    catch {
        Write-ModuleLog -Message "Failed while waiting for GDAP approval: $($_.Exception.Message)" -Level Error -Component 'GDAP' -ErrorRecord $_ -ThrowError
    }
}