[CmdletBinding()]
param (
    [string]
    $SCTaskNum,

    [switch]
    $Quiet
)
    
begin {
    $StartTime = Get-Date
    New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
}
    
process {
    $SCTaskSearch = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter ('active=true^short_description=Active Directory Service Account Provisioning') -Verbose
    switch ($PSBoundParameters.Keys) {
        'SCTaskNum' {
            $SCTaskSearch = $SCTaskSearch | Where-Object Number -EQ $SCTaskNum
        }
    }
    
    Switch (@($SCTaskSearch).count) {
        { $_ -le 0 } {
            Write-Verbose -Message "No Active Directory Service Account Provisioning tasks found." -Verbose
        }
        { $_ -ge 1 } {
            Write-Verbose -Message ("Number of Active Directory Service Account Provisioning tasks found: " + @($SCTaskSearch).count) -Verbose
        }
    }

    ForEach ($SCTask in $SCTaskSearch) {
        Clear-Variable -Name RITM, obj, NewITDADServiceAccountParams -ErrorAction SilentlyContinue
        Write-Verbose -Message ("Start " + $SCTask.Num)
        $Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId $SCTask.request_item.value -IncludeCustomVariable
        $RitmRequestedFor = Get-ITDServiceNowUser -SysId $Ritm.requested_for.value

        $obj = ($Ritm.CustomVariable.additional_comments.Value -split "`n")[2] | ConvertFrom-Json

        If ($Obj.ADDomain -ne 'nd.gov') {
            Write-Error -Message "Only nd.gov is supported, create account manually" -ErrorAction Stop
        }

        $NewITDADServiceAccountParams = @{
            SamAccountName     = $obj.SamAccountName;
            Description        = $obj.Description;
            PasswordstateList  = $obj.PasswordstateList;
            PasswordstateTitle = $obj.PasswordstateTitle;
            PasswordstateNotes = ("Requested via " + $RITM.number)
            Credential         = $PrvCred; #$Secret:svcitdiaasauto;
        }
        try {
            New-ITDADServiceAccount @NewITDADServiceAccountParams -Verbose -ErrorAction Stop
            $Notes = "New Active Directory account created."
            $AccountCreated = $true
        }
        catch [Microsoft.PowerShell.Commands.WriteErrorException] {
            Write-Error -Message $error[0]
            $AccountCreated = $false
        }
    
    
        $EndTime = Get-Date

        If ($PSBoundParameters.ContainsKey('Quiet') -and $Quiet -eq $true) {
            Write-Verbose -Message "Quiet mode enabled.  No ServiceNow interactions will be done." -Verbose
        }
        Else {
            Write-Verbose -Message "Quiet mode disabled.  ServiceNow CHG will be generated." -Verbose
            # create std chg and close it
            switch ($AccountCreated) {
                $true {
                    Write-Verbose -Message "AccountCreated true" -Verbose
                    Write-Verbose -Message "Generating SNow CHG" -Verbose
                    
                    #New-ITDServiceNowSession -Environment Test -Credential $Secret:SNowVMCred
                    $NewITDServiceNowChangeRequestParams = @{
                        TemplateName              = 'NDIT-SPS-Server Add/Chg/Del'
                        RequestedByUsername       = $RitmRequestedFor.user_name;
                        Category                  = 'Systems Platforms - Systems';
                        Subcategory               = 'Windows';
                        Impact                    = 3;
                        ShortDescription          = "New nd.gov Active Directory service account created - $UAJobId, " + $RITM.number;
                        Description               = "New nd.gov Active Directory service account created";
                        Justification             = "New nd.gov Active Directory service account required for zero-trust policies, following guidelines found in KB0016867";
                        Implementation            = "PSUniversal execution";
                        RiskImpactAnalysis        = "Low";
                        BackoutPlan               = "Delete the new user account"
                        TestPlan                  = "n/a"
                        WhoIsImpacted             = "Windows System Administrators";
                        StartTime                 = $StartTime
                        EndTime                   = $EndTime;
                        AssignmentGroup           = 'NDIT-Computer Systems Windows';
                        ChangeManagerUsername     = 'khellman';
                        ChangeCoordinatorUsername = 'gpgolberg';
                        AssignedToUsername        = $RitmRequestedFor.user_name;
                    }
        
                    $CHG = New-ITDServiceNowChangeRequest @NewITDServiceNowChangeRequestParams -Verbose
        
                    Update-ITDServiceNowRecord -ItemType "Change Request" -Number $CHG.Number.Value -Values @{
                        work_notes = $Notes;
                    }

                    Write-Verbose -Message ("Completing SNow " + $CHG.Number.value) -Verbose
                    $CompleteITDServiceNowChangeRequestParams = @{
                        Number = $CHG.Number.value
                        CloseCode = "Successful"
                        CloseNotes = ("New nd.gov Active Directory account " + $obj.ADDomain + "\" + $obj.SamAccountName + " created.")
                    }
                    Complete-ITDServiceNowChangeRequest @CompleteITDServiceNowChangeRequestParams -Verbose
    
                    New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
                
                    Write-Verbose -Message ("SCTASK " + $SCTask.Num + " success notes")
                    Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTask.Number -Values @{
                        work_notes = $Notes + "`n" + ($Chg.Number.value + " created for the work.");
                        close_notes = $Notes;
                        state = "Closed Complete";
                    }
                }
                $false {
                    Write-Verbose -Message "AccountCreated false" -Verbose
                    Write-Verbose -Message ("SCTASK " + $SCTask.Num + " failure notes")
                    $Message = "Error during account creation, requires human review.  PSU Job Id #$UAJobId"
                    Write-Warning -Message $Message
                    Write-Verbose -Message ("Update " + $SCTask.Number)
                    Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCtask.Number -Values @{
                        work_notes        = $Message;
                        short_description = $SCTask.short_description + " - HUMAN REVIEW"
                    }
                }
                Default {
                    Write-Verbose -Message "AccountCreated default" -Verbose
                    Write-Error -Message "AccountCreated variable is somehow not true or false... not sure how that happened.  Great work!"
                }
            }
        }
        Write-Verbose -Message ("End   " + $SCTask.Num)
    }
    
    
}

end {
    
}