# Variables à configurer
$Project = "abc-prj-np-mdf-001"
$Topic = "MindFlow:publish"
$Subscription = "Alerte:pull"
$Acknowledge = "Alerte:acknowledge"
$subject     = "Test subject"
$Message     = "Message lundi 26 mai Test en direct"
$APIUrl = "https://pubsub.googleapis.com/v1"

$PublishUrl = "$apiUrl/projects/$project/topics/$topic"
$PullUrl    = "$APIUrl/projects/$project/subscriptions/$subscription"

# Récupérer un jeton d'accès via gcloud (assurez-vous que gcloud est installé et configuré)
$AccessToken = "ya29.a0AW4XtxiaBCPy6Wp2dTnjTi-W0g-tMFw_aYNzChaFOg9yH7mYliW0WDOnisy99HLwHTTEI-eV7qbkCP_oea-d1rc1SNovVPAe1fLged__1xFN0hKYtk4ZlVMUnT_fNoC7DcG88I_PdYbc0SgSgBKvoM0szcGumHlBspJYUvxcGQaCgYKAWcSARESFQHGX2MiG1rXkcIBkOLbcXfDncySPw0181"

If (-not $accessToken) {
    Write-Error "Impossible d'obtenir un jeton d'accès. Vérifiez votre configuration gcloud."
    exit
}

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

# Publier le message sur le topic Pub/Sub
#$base64Message = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Message))

$payloadPublish = @{
    messages = @(
        @{
            data = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Message))
            attributes = @{
                subject = $subject
            }
        }
    )
} | ConvertTo-Json -Depth 10

$responsePublish = Invoke-RestMethod -Method Post -Uri $publishUrl -Headers $headers -Body $payloadPublish # -ContentType "application/json"
Write-Host "Message publié. Réponse :" $responsePublish.messageIds

########################################################################################

# Lire (pull) le message depuis la subscription Pub/Sub

cls

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

$responsePull = Invoke-RestMethod -Method Post -Uri $pullUrl -Headers $headers -Body $payloadPull # -ContentType "application/json"

If ($responsePull.receivedMessages) {
    Write-Host "Message tiré. Réponse : " $responsePull.receivedMessages
    Foreach ($message in $responsePull.receivedMessages) {
        $data = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($message.message.data))
        Write-Host "Received message: $data"

    }
}

########################################################################################

# Acquitter le message si présent
If ($responsePull.receivedMessages) {
     $ackIds = $responsePull.receivedMessages | ForEach-Object { $_.ackId }

     $ackUrl = "https://pubsub.googleapis.com/v1/projects/$project/subscriptions/$acknowledge"
     $payloadAck = @{
         ackIds = $ackIds
     } | ConvertTo-Json

     Invoke-RestMethod -Method Post -Uri $ackUrl -Headers $headers -Body $payloadAck -ContentType "application/json"
     Write-Host "Message(s) acquitté(s)."
}
Else {
     Write-Host "Aucun message reçu."
}