Function Get-EmailAddress {
    <#
    .SYNOPSIS
        Retrieves a user's email address from Active Directory.

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

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

    .EXAMPLE
        Get-EmailAddress -Name "Doe, John"
        Returns the email address for John Doe.

    .EXAMPLE
        "Doe, John" | Get-EmailAddress
        Returns the email address 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 `
                        -ErrorAction Stop
                }

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