<#
.SYNOPSIS
    A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
    A longer description of the function, its purpose, common use cases, etc.
.NOTES
    $StartTime & $EndTime
        Send local time in parameter as [datetime] object
        Function will convert the date object to UTC, and convert that result to a string via .ToString()
            API properties of start_date and end_date require datetime formatted as string
.LINK
    Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
    Test-MyTestFunction -Verbose
    Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>

function New-ITDServiceNowChangeRequestOG {
    [CmdletBinding()]
    param (
        [string]
        $RequestedByUsername,

        [Parameter(Mandatory = $true)]
        [string]
        $Category,

        [string]
        $Subcategory,

        [Parameter(Mandatory = $true)]
        [string]
        $ShortDescription,

        [Parameter(Mandatory = $true)]
        [string]
        $Description,

        [ValidateRange(1, 3)]
        [int]
        $Priority,

        [ValidateRange(1, 3)]
        [int]
        $Impact,

        [Parameter(Mandatory = $true)]
        [string]
        $Justification,

        [Parameter(Mandatory = $true)]
        [string]
        $Implementation,

        [Parameter(Mandatory = $true)]
        [string]
        $RiskImpactAnalysis,

        [Parameter(Mandatory = $true)]
        [string]
        $BackoutPlan,

        [Parameter(Mandatory = $true)]
        [string]
        $TestPlan,

        [Parameter(Mandatory = $true)]
        [string]
        $WhoIsImpacted,

        [Parameter(Mandatory = $true)]
        [string]
        $ChangeManagerUsername,

        [string]
        $ChangeCoordinatorUsername,

        [Parameter(Mandatory = $true)]
        [string]
        $AssignmentGroup,

        [string]
        $AssignedToUsername,

        [Parameter(Mandatory = $true)]
        [datetime]
        $StartTime,
        
        [Parameter(Mandatory = $true)]
        [datetime]
        $EndTime


    )
    
    begin {
        
    }
    
    process {
        <#payload = {
            "category": category,
            "u_subcategory": subCategory,
            "u_change_manager": chngMngrID,
            "assigned_to": userID,
            "u_change_coordinator": chngCoordID,
            "assignment_group": grpID,
            "short_description": shortDesc,
            "description": desc,
            "justification": justDesc,
            "implementation_plan": implmntPlan,
            "risk_impact_analysis": riskImpact,
            "backout_plan": backoutPlan,
            "test_plan": testPlan,
            "start_date": sTime,
            "end_date": eTime,
            "cab_required": False,
            }#>
            
        [PSCustomObject]$NewRecord = @{
            category             = $Category;
            u_subcategory        = $Subcategory
            impact               = $Impact;
            urgency              = $Urgency;
            short_description    = $ShortDescription;
            description          = $Description;
            justification        = $Justification;
            implementation_plan  = $Implementation;
            risk_impact_analysis = $RiskImpactAnalysis;
            backout_plan         = $BackoutPlan;
            test_plan            = $TestPlan
            u_who_is_impacted    = $WhoIsImpacted;
            start_date           = $StartTime.ToUniversalTime().ToString(); # see help/notes
            end_date             = $EndTime.ToUniversalTime().ToString(); # see help/notes
        }

        If ($RequestedBy) {
            $ReqBy = Get-ITDServiceNowUser -Username $RequestedBy
            If (@($ReqBy).count -gt 1) {
                Write-Error "Multiple requested users found, incident creation failed." -ErrorAction Stop
            }
            Else {
                $NewRecord += @{requested_by = $ReqBy.sys_id }
            }
        }

        If ($AssignmentGroup) {
            $AssGroup = Get-ITDServiceNowUserGroup -Name $AssignmentGroup
            If (@($AssGroup).count -gt 1) {
                Write-Error "Multiple assignment groups found, incident creation failed." -ErrorAction Stop
            }
            Else {
                $NewRecord += @{assignment_group = $AssGroup.sys_id }
            }
        }

        $ChgManagerUsername = Get-ITDServiceNowUser -Username $ChangeManagerUsername
        If (@($ChgManagerUsername).count -gt 1) {
            Write-Error "Multiple users found for ChangeManagerUsername, incident creation failed." -ErrorAction Stop
        }
        Else {
            $NewRecord += @{u_change_manager = $ChgManagerUsername.sys_id }
        }

        $ChgCoordUsername = Get-ITDServiceNowUser -Username $ChangeCoordinatorUsername
        If (@($ChgCoordUsername).count -gt 1) {
            Write-Error "Multiple users found for ChangeManagerUsername, incident creation failed." -ErrorAction Stop
        }
        Else {
            $NewRecord += @{u_change_coordinator = $ChgCoordUsername.sys_id }
        }

        If ($AssignedToUsername) {
            $AssTo = Get-ITDServiceNowUser -UserName $AssignedToUsername
            If (@($AssTo).count -gt 1) {
                Write-Error "Multiple assignment users found, incident creation failed." -ErrorAction Step
            }
            Else {
                $NewRecord += @{assigned_to = $AssTo.sys_id }
            }
        }

        Write-Verbose ($NewRecord | ConvertTo-Json)
            
        $InvokeRestMethodParams = @{
            Method      = 'Post';
            Uri         = ($Script:ServiceNowSession.Uri + "/api/now/table/change_request");
            Body        = $NewRecord | ConvertTo-Json;
            Headers     = $Script:ServiceNowSession.Headers;
            ContentType = "application/json"
        }

        #Write-Output $InvokeRestMethodParams
        $result = Invoke-RestMethod @InvokeRestMethodParams

    }
    
    end {
        Write-Output $result   
    }
}

