Function Get-DoDId {
    <#
    .SYNOPSIS
        Retrieves a user's DoD ID number (SAM Account Name).

    .DESCRIPTION
        Looks up a user in Active Directory by "Last, First" name format and
        returns their SAM Account Name (DoD ID number).

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

    .EXAMPLE
        Get-DoDId -Name "Doe, John"
        Returns the SAM Account Name for John Doe.

    .EXAMPLE
        "Doe, John", "Smith, Jane" | Get-DoDId
        Returns the SAM Account Names for multiple users 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) {
                    Write-Output $result.SamAccountName
                }
                else {
                    Write-Warning "No AD user found matching '$fullName'"
                }
            }
            catch {
                Write-Warning "Could not retrieve DoD ID for '$fullName'. Error: $($_.Exception.Message)"
            }
        }
    }
}
