$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'
$baseOrg = 'https://dev.azure.com/CN-Squad/_apis'
$repoId = 'ae7542f8-d76e-4a45-b8b2-745e18cd2f26'
$prId = 2135

# Pegar identity do usuario atual
$me = Invoke-RestMethod -Uri "https://app.vssps.visualstudio.com/_apis/profile/me?api-version=7.0" -Headers $h
Write-Host "Usuario: $($me.displayName) - ID: $($me.id)"

# Aprovar o PR com o ID correto do usuario
Write-Host "Aprovando PR..."
$voteBody = @{ vote = 10 } | ConvertTo-Json
try {
  $vote = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/pullrequests/$prId/reviewers/$($me.id)?api-version=7.0" -Method PUT -Headers $h -Body $voteBody -ErrorAction Stop
  Write-Host "  Voto registrado: $($vote.vote)" -ForegroundColor Green
} catch {
  Write-Host "  ERRO ao votar: $_" -ForegroundColor Red
}

# Tentar completar com bypassPolicy
$featureSha = '7a8a0128350d43d839118383414a1b0dc4f24e44'
$completeBody = @{
  status = 'completed'
  lastMergeSourceCommit = @{ commitId = $featureSha }
  completionOptions = @{
    mergeStrategy      = 'squash'
    deleteSourceBranch = $false
    bypassPolicy       = $true
    bypassReason       = 'Merge automatico - correcao de infra'
  }
} | ConvertTo-Json -Depth 5

Write-Host "Completando PR #$prId..."
try {
  $result = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/pullrequests/$prId`?api-version=7.0" -Method PATCH -Headers $h -Body $completeBody -ErrorAction Stop
  Write-Host "  Status: $($result.status)" -ForegroundColor Green
  if ($result.status -eq 'completed') {
    Write-Host "  Merge realizado com sucesso!" -ForegroundColor Green
  }
} catch {
  $errMsg = $_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue
  Write-Host "  ERRO: $($errMsg.message)" -ForegroundColor Red
}
