AzureRESTAPI.psm1

if (-not [System.Environment]::GetEnvironmentVariable('AZURE_AUTH_HEADER')) {
    [System.Environment]::SetEnvironmentVariable('AZURE_AUTH_HEADER', "Bearer $Env:SYSTEM_ACCESSTOKEN")
}

if (-not (Test-Path variable:global:AzureConsts)) {
    New-Variable -Name AzureConsts -Value ([psobject]@{
            ProjectName   = "$Env:SYSTEM_TEAMPROJECT";
            ProjectId     = "$Env:SYSTEM_TEAMPROJECTID";
            ProjectUri    = "${Env:SYSTEM_COLLECTIONURI}$Env:SYSTEM_TEAMPROJECTID/";
            CollectionId  = "$Env:SYSTEM_COLLECTIONID";
            CollectionUri = "$Env:SYSTEM_COLLECTIONURI";
        }) -Option Constant -Visibility Public -Scope Global
}

New-Variable -Name AzureRESTAPIConfigs -Value ([psobject]@{
        AuthHeader = "$Env:AZURE_AUTH_HEADER";
    }) -Visibility Public -Scope Global -Option ReadOnly


function Invoke-AzureRequest {
    [CmdletBinding()]
    param(
        [ValidateScript({ -not [string]::IsNullOrWhitespace($_.Trim()) })]
        [Parameter(Mandatory=$true)]
        [string]$Url,

        [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = 0,

        [hashtable]$Body,
        [hashtable]$Headers,

        [ValidateScript({ -not [string]::IsNullOrWhitespace($_.Trim()) })]
        [string]$ContentType = 'application/json',

        [ValidateScript({ -not [string]::IsNullOrWhitespace($_.Trim()) })]
        [string]$Accept = 'application/json',

        [switch]$WhatIf,
        [switch]$BypassRules,
        # Only provide this when you want to ignore http status check
        [int]$ExpectedStatus
    )

    process {
        $FinalHeaders = @{
            Authorization = $AzureRESTAPIConfigs.AuthHeader
        }
        $FinalHeaders += $Headers ?? @{}
        $FinalBody = $Body
        $EndpointDescriptor = $(Get-PSCallStack)[1].InvocationInfo.InvocationName
        $IsJsonish = $ContentType -ilike '*json*'

        if ($IsJsonish) {
            $FinalBody = ConvertTo-Json ($Body ?? @{}) -Depth 100
        }

        Write-Debug "Invoking $EndpointDescriptor API Request`nUrl => [$Method] $Url`nBody => $FinalBody"

        return
        $Req = @{
            Uri = $Url;
            Method = $Method;
            Headers = $Headers;
            ContentType = $ContentType;
        }

        if ($Body) {
            $Req['Body'] = $FinalBody
        }

        if ($ExpectedStatus -gt 0) {
            $Req['SkipHttpErrorCheck'] = $true
        }

        $Resp = Invoke-WebRequest @Req

        if (($ExpectedStatus -gt 0 -and $Resp.BaseResponse -ne $ExpectedStatus) -or ($ExpectedStatus -eq 0 -and $Resp.-not(BaseResponse.IsSuccessStatusCode))) {
            Write-Error $Resp.BaseResponse
        }
        elseif ($Accept -ilike '*json*') {
            $Resp.Content | ConvertFrom-Json
        }
        else { $Resp.Content }
    }
}

Export-ModuleMember -Variable AzureConsts, AzureRESTAPIConfigs -Function Invoke-AzureRequest