$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'
$repoId = 'ae7542f8-d76e-4a45-b8b2-745e18cd2f26'
$prId = 2135

# Verificar status do PR e policies
$pr = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/pullrequests/$prId`?api-version=7.0" -Headers $h
Write-Host "PR Status: $($pr.status)"
Write-Host "Merge Status: $($pr.mergeStatus)"
Write-Host "Is Draft: $($pr.isDraft)"

# Verificar policy evaluations
$policies = Invoke-RestMethod -Uri "$base/policy/evaluations?artifactId=vstfs:///CodeReview/CodeReviewId/$(($base -split '/')[4])/$prId`&api-version=7.0-preview.1" -Headers $h -ErrorAction SilentlyContinue
if ($policies) {
  Write-Host "`nPolicies bloqueando:"
  $policies.value | Where-Object { $_.status -ne 'approved' } | ForEach-Object {
    Write-Host "  - $($_.configuration.type.displayName): $($_.status)"
  }
}

# Tentar votar como aprovador
Write-Host "`nTentando aprovar o PR..."
$voteBody = @{ vote = 10 } | ConvertTo-Json
$vote = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/pullrequests/$prId/reviewers/me?api-version=7.0" -Method PUT -Headers $h -Body $voteBody -ErrorAction SilentlyContinue
if ($vote) {
  Write-Host "  Voto: $($vote.vote)" -ForegroundColor Green
}

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

Write-Host "Tentando completar 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 apos PATCH: $($result.status)" -ForegroundColor Green
} catch {
  Write-Host "  ERRO: $_" -ForegroundColor Red
}
