Function Get-UserPrincipalName {
    <#
    .SYNOPSIS
        Retrieves a user's UserPrincipalName (UPN) from Active Directory.

    .DESCRIPTION
        Looks up a user in Active Directory by "Last, First" name format and
        returns their UserPrincipalName.

    .PARAMETER Name
        The user's name in "Last, First" format. The comma separates last name
        from first name.

    .EXAMPLE
        Get-UserPrincipalName -Name "Doe, John"
        Returns the UPN for John Doe.

    .EXAMPLE
        "Doe, John" | Get-UserPrincipalName
        Returns the UPN for a user passed via the pipeline.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [string[]]$Name
    )

    Begin {
        $searchBase = "OU=McGuire AFB Users,OU=McGuire AFB,OU=AFCONUSWEST,OU=Bases,DC=AREA52,DC=AFNOAPPS,DC=USAF,DC=MIL"
    }

    Process {
        foreach ($fullName in $Name) {
            $parts = $fullName.Split(",")
            $last  = $parts[0].Trim()
            $first = if ($parts.Count -gt 1) { $parts[1].Trim() } else { "" }

            $ldapFilter = "Name -like '$last.$first*'"
            Write-Verbose "Searching AD with filter: $ldapFilter"

            try {
                if ($script:SimulationMode) {
                    $userFile = Get-ToolADDataPath -FileName 'AFUsersDB_AD.json'
                    $result = Find-ToolADJsonObjectByPrefix -FilePath $userFile -PropertyName 'Name' -Prefix "$last.$first"
                } else {
                    $result = Get-ADUser `
                        -SearchBase $searchBase `
                        -Filter $ldapFilter `
                        -Properties emailaddress, EmployeeType `
                        -ErrorAction Stop
                }

                if ($result -and $result.UserPrincipalName) {
                    Write-Output $result.UserPrincipalName
                }
                else {
                    Write-Warning "No UserPrincipalName found for '$fullName'"
                }
            }
            catch {
                Write-Warning "Could not retrieve UPN for '$fullName'. Error: $($_.Exception.Message)"
            }
        }
    }
}
