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

$buildIds = @(6181, 6182, 6183, 6185, 6186)  # mfe-shell, mfe-auth, mfe-shell-oci, mfe-person, mfe-poc
# mfe-user nao apareceu, buscar separado
$defs = Invoke-RestMethod -Uri "$base/build/definitions?name=mfe-user&api-version=7.0" -Headers $h
if ($defs.count -gt 0) {
  $defId = $defs.value[0].id
  $ub = Invoke-RestMethod -Uri "$base/build/builds?definitions=$defId&branchName=refs/heads/devops&`$top=1&api-version=7.0" -Headers $h
  if ($ub.count -gt 0) { $buildIds += $ub.value[0].id }
}

Write-Host "Aguardando builds: $($buildIds -join ', ')" -ForegroundColor Cyan

for ($i = 0; $i -lt 30; $i++) {
  Start-Sleep -Seconds 15
  $ts = Get-Date -Format 'HH:mm:ss'
  $pending = 0
  $status = @()

  foreach ($bid in $buildIds) {
    $b = Invoke-RestMethod -Uri "$base/build/builds/$bid`?api-version=7.0" -Headers $h
    $result = if ($b.result) { $b.result } else { '...' }
    $status += "$($b.definition.name)=$result"
    if ($b.status -ne 'completed') { $pending++ }
  }

  Write-Host "$ts  $($status -join '  ')"
  if ($pending -eq 0) { break }
}

Write-Host ""
Write-Host "Resumo final:" -ForegroundColor Cyan
foreach ($bid in $buildIds) {
  $b = Invoke-RestMethod -Uri "$base/build/builds/$bid`?api-version=7.0" -Headers $h
  $result = if ($b.result) { $b.result } else { $b.status }
  $icon = if ($result -eq 'succeeded') { 'OK' } else { 'FALHOU' }
  Write-Host "  [$icon] $($b.definition.name) (build $bid): $result"

  if ($result -eq 'failed') {
    $vr = $b.validationResults
    if ($vr) {
      $vr | Select-Object -First 2 | ForEach-Object { Write-Host "     erro: $($_.message)" }
    }
  }
}
