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

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

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $CPU = 1,
    
    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $MemoryGB = 4,

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

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $DiskSwapGB = ($MemoryGB + 1),

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

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

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

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $VMEnvironment = 'Test',
    
    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $Datacenter = 'Mandan',

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $AppName = 'ITD-POC-zmeier',

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [int]
    $StartupPriority = 5,

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

switch ($PSCmdlet.ParameterSetName) {
    'ManualEntry' {
        $NewITDWindowsVmVMwareParams = @{
            FQDN                  = $FQDN;
            CPU                   = $CPU;
            MemoryGB              = $MemoryGB;
            DiskOsGB              = $DiskOsGB;
            DiskSwapGB            = $DiskSwapGB;
            DiskDataGB            = $DiskDataGB;
            Subnet                = $Subnet;
            OS                    = $OS;
            VMEnvironment         = $VMEnvironment;
            Datacenter            = $Datacenter;
            AppName               = $AppName;
            StartupPriority       = $StartupPriority;
            LicensingRestrictions = $LicensingRestrictions;
        }
    }
    '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]

        $NewITDWindowsVmVMwareParams = @{
            FQDN                  = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
            CPU                   = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );
            MemoryGB              = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );
            DiskOsGB              = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
            DiskSwapGB            = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_2_swap_disk );
            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 );
            Datacenter            = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).data_center );
            AppName               = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
            StartupPriority       = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).startup_priority );
            LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
        }
    }
}

Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdiaasauto -Verbose

Write-Verbose -Message "Attempt server provisioning" -Verbose
Write-Verbose -Message $NewITDWindowsVmVMwareParams
try {
    New-ITDWindowsVmVMwareStep1 @NewITDWindowsVmVMwareParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
    Write-Verbose -Message "New-ITDWindowsVmVMwareStep1 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 = ("VMware build step 1 errored. $Msg.  `nPSU Job Id #" + $UAJob.Id + "  `n" + $ErrorText)
                    state      = 'Closed Incomplete'
                }
            }
        }
    }
    throw
}

Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter

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 = ("VMware build step 1 complete.  `nPSU Job Id #" + $UAJob.Id)
                }
            }
            $false {
                Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
                    work_notes = ("VMware build step 1 errored, needs human review.  `nPSU Job Id #" + $UAJob.Id)
                }
            }
        }
    }
}