[CmdletBinding()] #
param (
    [Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
    $SCTaskNum,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $FQDN,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry', HelpMessage = "Example: Standard_D4ds_v5")]
    [string]
    $VmSize,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $DiskOsGB = 128,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $DiskDataGB = 20,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $Subnet,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $OS = 'Windows Server 2022',

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $VMEnvironment,
        
    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $AppName,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $LicensingRestrictions = 'No Licensing Restrictions',

    [string]
    $ResourceGroupNameOverride,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [ValidateSet('No Zone', 'Zone 1', 'Zone 2', 'Zone 3')]
    [string]
    $AvailabilityZone
)

switch ($PSCmdlet.ParameterSetName) {
    'ManualEntry' {
        $NewITDWindowsVmAzureParams = @{
            FQDN                  = $FQDN;
            AppName               = $AppName;
            VmSize                = $VmSize;
            #CPU                   = $CPU;
            #MemoryGB              = $MemoryGB;
            DiskOsGB              = $DiskOsGB;
            DiskDataGB            = $DiskDataGB;
            Subnet                = $Subnet;
            OS                    = $OS;
            VMEnvironment         = $VMEnvironment;
            LicensingRestrictions = $LicensingRestrictions;
        }
        switch ($PSBoundParameters.Keys) {
            'ResourceGroupNameOverride' { $NewITDWindowsVmAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride } }
            'AvailabilityZone' { $NewITDWindowsVmAzureParams += @{ AvailabilityZone = $AvailabilityZone } }
        }
    }
    'FromSCTask' {
        Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
        switch ($UAJob.ComputerName) {
            "ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
            "ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
        }
        Write-Verbose -Message "New-ITDServiceNowSession" -Verbose
        New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred

        $SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
        $Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable

        $FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]

        $AvailabilityZone = 

        $NewITDWindowsVmAzureParams = @{
            FQDN                  = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
            VmSize                = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).azure_vm_size );
            DiskOsGB              = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
            DiskDataGB            = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
            Subnet                = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
            OS                    = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
            VMEnvironment         = ( $Ritm.customvariable.environment.value );
            AppName               = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
            LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
        }

        switch ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).zone ) {
            'Zone 1' { $NewITDWindowsVMAzureParams += @{ AvailabilityZone = 1 } }
            'Zone 2' { $NewITDWindowsVMAzureParams += @{ AvailabilityZone = 2 } }
            'Zone 3' { $NewITDWindowsVMAzureParams += @{ AvailabilityZone = 3 } }
        }

        switch ($PSBoundParameters.Keys) {
            'ResourceGroupNameOverride' {
                Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
                $NewITDWindowsVMAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride } 
            }
            <#'AvailabilityZone' {
                Write-Warning -Message "ResourceGroupNameOverride found $AvailabilityZone"
                $NewITDWindowsVMAzureParams += @{ AvailabilityZone = $AvailabilityZone } 
            }#>
            <# 'VMSizeOverride' {
                Write-Warning -Message "VMSizeOverride found $VMSizeOverride"
                $NewITDWindowsVMAzureParams += @{ VMSizeOverride = $VMSizeOverride } 
            }#>
        }
        <#If ($NewITDWindowsVmAzureParams.VMSizeOverride) {
            # do nothing
        } Else {
            $NewITDWindowsVMAzureParams += @{ CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );}
            $NewITDWindowsVMAzureParams += @{ MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );}
        }#>
    }
}

Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = $Secret:azure_iaasserviceprincipal
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId

Write-Verbose -Message "Attempt server provisioning" -Verbose
Write-Verbose -Message "NewITDWindowsVMAzureParams:" -Verbose
Write-Verbose -Message ("FQDN " + $NewITDWindowsVMAzureParams.FQDN) -Verbose
Write-Verbose -Message ("VmSize " + $NewITDWindowsVMAzureParams.VmSize) -Verbose
Write-Verbose -Message ("DiskOsGB " + $NewITDWindowsVMAzureParams.DiskOsGB) -Verbose
Write-Verbose -Message ("DiskDataGB " + $NewITDWindowsVMAzureParams.DiskDataGB) -Verbose
Write-Verbose -Message ("Subnet " + $NewITDWindowsVMAzureParams.Subnet) -Verbose
Write-Verbose -Message ("OS " + $NewITDWindowsVMAzureParams.OS) -Verbose
Write-Verbose -Message ("VMEnvironment " + $NewITDWindowsVMAzureParams.Environment) -Verbose
Write-Verbose -Message ("AppName " + $NewITDWindowsVMAzureParams.AppName) -Verbose
Write-Verbose -Message ("LicensingRestrictions " + $NewITDWindowsVMAzureParams.LicensingRestrictions) -Verbose
try {
    New-ITDWindowsVmAzureStep1 @NewITDWindowsVmAzureParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
    Write-Verbose -Message "New-ITDWindowsVmAzureStep1 function completed"
    $Step1Complete = $true
}
catch {
    $Step1Complete = $false
    switch ($PSCmdlet.ParameterSetName) {
        'FromSCTask' {
            $ErrorText = ($_.ErrorDetails.message | ConvertFrom-Json).text
            If ($ErrorText -match "Cannot find 1 available IP address" ) {
                $Msg = "Resolve the issue and resubmit the Server Build Request catalog item.  Setting $SCTaskNum State to Closed Incomplete"
                Write-Warning -Message $Msg
                Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
                    work_notes = ("Azure build step 1 errored. $Msg.  `nPSU Job Id #" + $UAJob.Id + "  `n" + $ErrorText)
                    state      = 'Closed Incomplete'
                }
            }
        }
    }
    throw
}


switch ($PSCmdlet.ParameterSetName) {
    'FromSCTask' {
        Write-Verbose -Message ("Update " + $SCTaskNum + " with Step 1 status") -Verbose
        switch ($Step1Complete) {
            $true {
                Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
                    work_notes = ("Azure build step 1 complete.  `nPSU Job Id #" + $UAJob.Id)
                }
            }
            $false {
                Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
                    work_notes = ("Azure build step 1 errored, needs human review.  `nPSU Job Id #" + $UAJob.Id)
                }
            }
        }
    }
}