$projectId        = "abc-prj-mdf-001"
$subscriptionName = "Alerte:pull"
$Acknowledge      = "Alerte:acknowledge"
$AccessToken      = "ya29.a0AW4Xtxhr8rj3E7RdTI8EFlWlaEFW3ZmqC4suDspyzi5WdEkNK6xGafJxzmkan6obZjRNuV1rKNyi1MBJAVhz0HQIdjd1B2nH10pq0N9WkQNMVOQM-9SDtsI1_ubVgww1uv7lZI16MvjDOyVmHeD92KtLhb4bQJEmtQsrpEm0aCgYKAUYSARESFQHGX2MiZux4MfqHTzFxi-5xR0k_Ww0182"

$response = $Null

$apiUrl = "https://pubsub.googleapis.com/v1/projects/$projectId/subscriptions/$subscriptionName"

$headers = @{
    "Authorization"  = "Bearer $AccessToken"
    "accept"         = "application/json"
    "Content-Type"   = "application/json"
}

$body = @{
     maxMessages = 100
} | ConvertTo-Json -Depth 10

$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Headers $headers -Body $body

#Write-Host "Message tiré. Réponse : " $response.receivedMessages

# Afficher les messages
If ($response.receivedMessages) {
    Foreach ($message in $response.receivedMessages) {
        $data = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($message.message.data))
        Write-host "*******************************"
        Write-Host "Received message: $data"
        $message.message.messageId
        #$message.message.publishTime
        #$message.message.attributes.subject
        Write-host "*******************************"

#        $ackIds = $response.receivedMessages | ForEach-Object { $_.ackId }

        # Accuser réception du message
#        $ackId = $message.message.messageId
#        $ackUrl = "https://pubsub.googleapis.com/v1/projects/$projectId/subscriptions/$Acknowledge"

#        $ackBody = @{
#            ackIds = @($ackId)
#        } | ConvertTo-Json

#        Invoke-RestMethod -Uri $ackUrl -Method Post -Headers $headers -Body $ackBody
    }
}
Else {
     Write-Host "No messages received."
}
