Function Find-UDrive {
    <#
    .SYNOPSIS
        Locates a user's U: drive folder on the network share.

    .DESCRIPTION
        Searches the standard U Drive paths for the target user's home folder
        and returns the full path if found.

    .PARAMETER UserName
        The name of the user whose U Drive to find. Resolved via Active Directory.

    .EXAMPLE
        Find-UDrive -UserName 'Doe.John'
        Returns the full UNC path to John Doe's U Drive folder if it exists.

    .EXAMPLE
        'Doe.John' | Find-UDrive
        Finds the U Drive for a user passed via the pipeline.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string[]]$UserName
    )

    Begin {
        $UserName = @(Split-ToolArgumentList -Value $UserName)
        $uDriveRoots = @(Get-ToolUDriveRoots)
    }

    Process {
        foreach ($user in $UserName) {
            if ([string]::IsNullOrWhiteSpace($user)) {
                Write-Warning "Empty user name provided."
                continue
            }

            try {
                $adUser = Get-ToolADUser -Identity $user -ErrorAction Stop
                $folderName = $adUser.Name
                Write-Verbose "Searching for U Drive folder: '$folderName'"
            }
            catch {
                Write-Warning "Could not resolve user '$user' in Active Directory. Error: $($_.Exception.Message)"
                continue
            }

            $found = $null
            foreach ($root in $uDriveRoots) {
                if (-not (Test-Path $root)) {
                    Write-Verbose "Root path not accessible: $root"
                    continue
                }
                try {
                    $items = Get-ChildItem -Path $root -ErrorAction Stop
                    $match = $items | Where-Object { $_.Name -eq $folderName } | Select-Object -First 1
                    if ($match) {
                        $found = $match.FullName
                        Write-Verbose "Found U Drive at: $found"
                        break
                    }
                }
                catch {
                    Write-Verbose "Could not read '$root': $($_.Exception.Message)"
                }
            }

            if ($found) {
                Write-Output $found
            }
            else {
                Write-Verbose "No U Drive found for '$folderName'"
                Write-Output $null
            }
        }
    }
}
