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

# 1. Achar o repo azure-pipelines-templates
$repos = Invoke-RestMethod -Uri "$base/git/repositories?api-version=7.0" -Headers $h
$repo = $repos.value | Where-Object { $_.name -eq 'azure-pipelines-templates' }

if (-not $repo) {
  Write-Host "ERRO: repo azure-pipelines-templates nao encontrado" -ForegroundColor Red
  $repos.value | Select-Object name, id | Format-Table
  exit 1
}

Write-Host "Repo: $($repo.name) - ID: $($repo.id)" -ForegroundColor Cyan
$repoId = $repo.id

# 2. Pegar SHA da feature branch
$featureRef = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/refs?filter=heads/feature/cd-deploy-oci-oke`&api-version=7.0" -Headers $h
if ($featureRef.count -eq 0) {
  Write-Host "ERRO: branch feature/cd-deploy-oci-oke nao encontrada" -ForegroundColor Red
  exit 1
}
$featureSha = $featureRef.value[0].objectId
Write-Host "  SHA feature: $featureSha"

# 3. Pegar SHA do main
$mainRef = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/refs?filter=heads/main`&api-version=7.0" -Headers $h
if ($mainRef.count -eq 0) {
  Write-Host "ERRO: branch main nao encontrada" -ForegroundColor Red
  exit 1
}
$mainSha = $mainRef.value[0].objectId
Write-Host "  SHA main: $mainSha"

# 4. Criar PR de feature/cd-deploy-oci-oke -> main
$prBody = @{
  title         = 'chore: merge feature/cd-deploy-oci-oke into main'
  description   = 'Merge dos templates OCI/OKE para main'
  sourceRefName = 'refs/heads/feature/cd-deploy-oci-oke'
  targetRefName = 'refs/heads/main'
  completionOptions = @{
    mergeStrategy      = 'squash'
    deleteSourceBranch = $false
  }
} | ConvertTo-Json -Depth 5

Write-Host "Criando PR..." -ForegroundColor Cyan
$pr = Invoke-RestMethod -Uri "$base/git/repositories/$repoId/pullrequests?api-version=7.0" -Method POST -Headers $h -Body $prBody -ErrorAction Stop
$prId = $pr.pullRequestId
Write-Host "  PR criado: #$prId" -ForegroundColor Green

# 5. Completar o PR (merge)
$completeBody = @{
  status = 'completed'
  lastMergeSourceCommit = @{ commitId = $featureSha }
  completionOptions = @{
    mergeStrategy      = 'squash'
    deleteSourceBranch = $false
  }
} | ConvertTo-Json -Depth 5

Write-Host "  Completando PR #$prId..." -ForegroundColor Cyan
$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
