Public/ps1/Html/Get-ApprxrAuthenticationRoute.ps1

function Get-ApprxrAuthenticationRoute {
    param(
        $hostURI,
        $channelId,
        $id,
        $type
    )

    # Check if debug mode is enabled
    $debugMode = $false
    try {
        $debugConfig = Get-ApprxrConfigurationValue -name "ApprxrHtmlDebugMode" -ErrorAction SilentlyContinue
        if ($debugConfig -and ($debugConfig -eq $true -or $debugConfig -eq "true" -or $debugConfig -eq "1")) {
            $debugMode = $true
        }
    } catch {
        # Configuration value not found, continue without debug mode
    }

    if ($debugMode) {
        Log "[Get-ApprxrAuthenticationRoute] DEBUG: Starting with parameters - hostURI: $hostURI, channelId: $channelId, id: $id, type: $type"
    } else {
        Log "[Get-ApprxrAuthenticationRoute] INFO: Starting authentication route lookup"
    }

    $authenticationPath = @{
        hostUri = $hostURI
        channelId = $channelId
        id = $id
        type = $type
    }

    # Extract protocol and host (including port) from hostUri
    $baseUri = $null
    if ($authenticationPath.hostUri) {
        try {
            $uri = [System.Uri]$authenticationPath.hostUri
            # Reconstruct base URI with scheme and authority (host:port)
            $baseUri = "$($uri.Scheme)://$($uri.Authority)"
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Extracted base URI from hostUri: $baseUri"
            }
        } catch {
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Could not parse hostUri as URI: $_"
            }
        }
    }


    # Determine the authentication id based on the provided parameters
    # Try each lookup method in order and check if credentials are found
    $authenticationId = $null
    $authenticationInformation = $null
    $lookupMethods = @()

    # Method 1: Try explicit id first
    if ($authenticationPath.id) {
        $lookupMethods += @{
            name = "Explicit ID"
            id = $authenticationPath.id
            debug = "Using explicit id parameter: $($authenticationPath.id)"
        }
    }
    
    # Method 2: Try hostUri + channelId
    if ($authenticationPath.hostUri -and $authenticationPath.channelId) {
        $lookupMethods += @{
            name = "HostUri + ChannelId"
            id = $authenticationPath.hostUri + $authenticationPath.channelId
            debug = "Using hostUri + channelId: $($authenticationPath.hostUri) + $($authenticationPath.channelId)"
        }
    }
    
    # Method 3: Try hostUri + type
    if ($authenticationPath.hostUri -and $authenticationPath.type) {
        $lookupMethods += @{
            name = "HostUri + Type"
            id = $authenticationPath.hostUri + $authenticationPath.type
            debug = "Using hostUri + type: $($authenticationPath.hostUri) + $($authenticationPath.type)"
        }
    }
    
    # Method 4: Try hostUri only
    if ($authenticationPath.hostUri) {
        $lookupMethods += @{
            name = "HostUri only"
            id = $authenticationPath.hostUri
            debug = "Using hostUri only: $($authenticationPath.hostUri)"
        }
    }

    # Try each lookup method in sequence until credentials are found
    foreach ($method in $lookupMethods) {
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: Trying lookup method '$($method.name)' - $($method.debug)"
        }
        
        $candidateId = Get-ApprxrAuthenticationId -channelId $authenticationPath.channelId -id $method.id -hostURI $authenticationPath.hostUri -type $authenticationPath.type
        
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: Generated authenticationId: $candidateId"
        }
        
        # Try to retrieve configuration for this ID
        $candidateInformation = Get-ApprxrConfigurationValue -name $candidateId -secure -ErrorAction SilentlyContinue
        
        if ($candidateInformation) {
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Found credentials for method '$($method.name)' with ID '$candidateId'"
            }
            $authenticationId = $candidateId
            $authenticationInformation = $candidateInformation
            break
        } else {
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: No credentials found for method '$($method.name)' with ID '$candidateId', trying next method..."
            }
        }
    }

    # If no exact match found and baseUri is available, try to find any configuration containing baseUri
    if (-not $authenticationInformation -and $baseUri) {
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: No exact match found, searching for configuration with matching base URI: $baseUri"
        }
        
        # Search for configs containing the base URI
        try {
            $allConfigs = Get-ApprxrConfiguration
            $candidates = @()
            
            # Collect all candidate configurations containing baseUri
            foreach ($configKey in $allConfigs.PSObject.Properties) {
                $candidateId = $configKey.Name
                
                # Filter 1: Config name must contain baseUri
                if (-not $candidateId.Contains($baseUri)) {
                    continue
                }
                
                # Filter 2: Skip NTLM entries
                if ($candidateId.Contains("NTLM")) {
                    $candidateIdToCheck = $candidateId.Replace("NTLM", "")
                } else {
                    continue
                }
                
                # Filter 3: Check if the remainder is contained in hostUri
                if ($authenticationPath.hostUri.Contains($candidateIdToCheck)) {
                   
                    $candidates += @{
                        id = $candidateId
                    }
                    if ($debugMode) {
                        Log "[Get-ApprxrAuthenticationRoute] DEBUG: Found candidate - ID: '$candidateId', Remainder: '$remainder'"
                    }
                }
            }
            
            # Use the longest matching remainder (most specific match)
            if ($candidates.Count -gt 0) {
                $bestMatch = $candidates | Sort-Object -Property remainderLength -Descending | Select-Object -First 1
                if ($debugMode) {
                    Log "[Get-ApprxrAuthenticationRoute] DEBUG: Using best match with ID '$($bestMatch.id)'"
                }
                $authenticationId = $bestMatch.id
                $authenticationInformation = Get-ApprxrConfigurationValue -name $authenticationId -secure -ErrorAction SilentlyContinue
            }
        } catch {
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Error searching for matching configuration: $_"
            }
        }
    }

    if ($debugMode) {
        if ($authenticationId) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: Successfully found authentication with ID '$authenticationId'"
        } else {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: No credentials found using any lookup method"
        }
    }

    if ($authenticationInformation) {
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: Parsing authentication information"
        }
        $authObj = $authenticationInformation | ConvertFrom-Json
        
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: Authentication type: $($authObj.type)" 
        }
        
        if ($authObj.type -eq 'NTLM') {
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Returning NTLM authentication with Negotiate scheme" 
            }
            $returnObj = [PSCustomObject]@{
                username = $authObj.username
                password = $authObj.password
                Authentication = "Negotiate"
            }
            return $returnObj
        } else {
            # Return authentication object for other types
            if ($debugMode) {
                Log "[Get-ApprxrAuthenticationRoute] DEBUG: Returning authentication object for type: $($authObj.type)" 
            }
            return $authObj
        }
    } else {
        # No authentication found
        if ($debugMode) {
            Log "[Get-ApprxrAuthenticationRoute] DEBUG: No authentication information found"
        }
        return $null
    }
}