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

$ms_repos = @{
  'ms-auth-external' = '976a0237-6006-4dae-a084-f054c815d601'
  'ms-auth-sso'      = '9932e1e0-48ab-417a-b712-36e3b618d758'
  'ms-barramento'    = 'ce4eff9f-0d40-4e27-b210-8c18b87d03f0'
  'ms-belt'          = 'f6223ed1-ab1e-47f9-8ec9-e0ca05c8feac'
  'ms-notify'        = '76c0279c-55d7-4001-97ed-8d279f7baa07'
  'ms-parameters'    = '4de79bf2-403b-4e60-ba36-87449ccbdc34'
  'ms-person'        = '58f9c27e-9f46-4e4c-b1fb-1b2ff63e021b'
  'ms-poc'           = '7e85222f-c166-4d52-8d37-3cf6ebeaeefa'
  'ms-user'          = '24bdf218-522a-45e2-8a31-96db3962997d'
}

foreach ($name in $ms_repos.Keys | Sort-Object) {
  $id = $ms_repos[$name]
  Write-Host "=== $name ===" -ForegroundColor Cyan

  # 1. Pegar commit atual do branch devops
  try {
    $ref = Invoke-RestMethod -Uri "$base/git/repositories/$id/refs?filter=heads/devops&api-version=7.0" -Headers $h -ErrorAction Stop
    $oldSha = $ref.value[0].objectId
    Write-Host "  SHA devops: $oldSha"
  } catch {
    Write-Host "  ERRO: nao consegui pegar SHA do devops" -ForegroundColor Red
    continue
  }

  # 2. Pegar conteudo atual do pipeline
  try {
    $current = Invoke-RestMethod -Uri "$base/git/repositories/$id/items?path=/azure-pipelines.yaml&versionDescriptor.version=devops&api-version=7.0" -Headers $h -ErrorAction Stop
  } catch {
    Write-Host "  ERRO: nao encontrei azure-pipelines.yaml" -ForegroundColor Red
    continue
  }

  # 3. Aplicar as correcoes
  $newContent = $current

  # P1: Corrige template branch feature/cd-deploy-oci-oke -> main
  $newContent = $newContent -replace 'refs/heads/feature/cd-deploy-oci-oke', 'refs/heads/main'

  # P2: ms-barramento especifico - corrige trigger e default
  if ($name -eq 'ms-barramento') {
    # Corrige condition de deploy: 'develop' -> 'devops'
    $newContent = $newContent -replace "eq\(variables\['Build\.SourceBranchName'\], 'develop'\)", "eq(variables['Build.SourceBranchName'], 'devops')"
    # Corrige default deployTarget: aws -> oci-argocd
    $newContent = $newContent -replace "default: aws`n    values: \[aws, oci-argocd\]", "default: oci-argocd`n    values: [aws, oci-argocd]"
  }

  if ($newContent -eq $current) {
    Write-Host "  Sem alteracoes necessarias." -ForegroundColor Yellow
    continue
  }

  # 4. Fazer push com o conteudo atualizado
  $contentBytes = [System.Text.Encoding]::UTF8.GetBytes($newContent)
  $contentB64 = [Convert]::ToBase64String($contentBytes)

  $body = @{
    refUpdates = @(@{ name = 'refs/heads/devops'; oldObjectId = $oldSha })
    commits = @(@{
      comment = "fix(pipeline): atualiza template ref para main e corrige deploy target OCI"
      changes = @(@{
        changeType = 'edit'
        item = @{ path = '/azure-pipelines.yaml' }
        newContent = @{ content = $newContent; 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 {
    Write-Host "  ERRO ao fazer push: $_" -ForegroundColor Red
  }
}
