$p = '19mNqNXIoZ4c3EriFNfzfkgpGNOvLjpOqqZnTFXKnzjxWJ5zURjgJQQJ99CBACAAAAAamI5kAAASAZDOAMPp'
$t = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(':' + $p))
$h = @{ Authorization = 'Basic ' + $t; 'Content-Type' = 'application/json' }
$base = 'https://dev.azure.com/CN-Squad/Invista%20FIDC%20-%20Nexus/_apis'

Write-Host "Monitorando aprovacoes por 3 minutos (polling 10s)..." -ForegroundColor Cyan

for ($i = 0; $i -lt 18; $i++) {
  Start-Sleep -Seconds 10

  $a = Invoke-RestMethod -Uri "$base/pipelines/approvals?state=pending&api-version=7.1-preview.1" -Headers $h
  $ts = Get-Date -Format 'HH:mm:ss'

  if ($a.count -eq 0) {
    Write-Host "$ts  sem aprovacoes pendentes" -ForegroundColor Gray
    continue
  }

  Write-Host "$ts  $($a.count) aprovacao(oes) pendente(s) — aprovando..." -ForegroundColor Yellow

  $items = @($a.value | ForEach-Object {
    @{ approvalId = $_.id; status = 'approved'; comment = 'Aprovado automaticamente via API' }
  })
  $body = ConvertTo-Json -InputObject $items -Depth 5

  $result = Invoke-RestMethod `
    -Uri "$base/pipelines/approvals?api-version=7.1-preview.1" `
    -Method PATCH -Headers $h -Body $body

  $result.value | ForEach-Object {
    Write-Host "  $($_.id) -> $($_.status)" -ForegroundColor Green
  }
}

Write-Host "Monitoramento encerrado." -ForegroundColor Cyan
