$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'

$mfe_repos = [ordered]@{
  'mfe-shell'  = '9f652079-76d7-4415-8c26-e40fdbcb6120'
  'mfe-auth'   = '23a19757-99e8-41c1-8b2c-a4921fe3795c'
  'mfe-user'   = '2eea9c4e-195e-4fb6-ae0b-2da1a560bcdc'
  'mfe-person' = '8580c8ba-57ab-40bd-9bc0-e967b40a4f39'
  'mfe-poc'    = '2090316d-09cc-4379-b821-85c874006e0a'
}

foreach ($name in $mfe_repos.Keys) {
  $id = $mfe_repos[$name]
  Write-Host "=== $name ===" -ForegroundColor Cyan

  $ref = Invoke-RestMethod -Uri "$base/git/repositories/$id/refs?filter=heads/devops&api-version=7.0" -Headers $h
  $oldSha = $ref.value[0].objectId

  # Faz um commit no .trigger para re-disparar a pipeline
  $body = @{
    refUpdates = @(@{ name = 'refs/heads/devops'; oldObjectId = $oldSha })
    commits = @(@{
      comment = "ci: re-trigger pipeline apos correcao do template"
      changes = @(@{
        changeType = 'add'
        item = @{ path = '/.trigger' }
        newContent = @{ content = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); contentType = 'rawtext' }
      })
    })
  } | ConvertTo-Json -Depth 10

  try {
    $result = Invoke-RestMethod -Uri "$base/git/repositories/$id/pushes?api-version=7.0" -Method POST -Headers $h -Body $body -ErrorAction Stop
    Write-Host "  OK - commit: $($result.commits[0].commitId)" -ForegroundColor Green
  } catch {
    # Arquivo .trigger pode ja existir — tentar com edit
    $body2 = @{
      refUpdates = @(@{ name = 'refs/heads/devops'; oldObjectId = $oldSha })
      commits = @(@{
        comment = "ci: re-trigger pipeline apos correcao do template"
        changes = @(@{
          changeType = 'edit'
          item = @{ path = '/.trigger' }
          newContent = @{ content = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); contentType = 'rawtext' }
        })
      })
    } | ConvertTo-Json -Depth 10
    try {
      $result2 = Invoke-RestMethod -Uri "$base/git/repositories/$id/pushes?api-version=7.0" -Method POST -Headers $h -Body $body2 -ErrorAction Stop
      Write-Host "  OK (edit) - commit: $($result2.commits[0].commitId)" -ForegroundColor Green
    } catch {
      Write-Host "  ERRO: $_" -ForegroundColor Red
    }
  }
}

Write-Host ""
Write-Host "Pipelines re-disparadas. Monitorando aprovacoes por 3 min..." -ForegroundColor Cyan
