$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'
$projectId = '28c26924-b0a7-485d-b8c2-c86e48377e85'
$vgId = 34

# Ler VG atual como string raw
$wc = New-Object System.Net.WebClient
$wc.Headers['Authorization'] = 'Basic ' + $t
$raw = $wc.DownloadString("$base/distributedtask/variablegroups/$vgId`?api-version=7.0")

# Usar .NET JSON para remover a chave
Add-Type -AssemblyName System.Web.Extensions
$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$serializer.MaxJsonLength = 10000000

$obj = $serializer.DeserializeObject($raw)

# Remover OCIR_REPOSITORY_NAME das variaveis
if ($obj['variables'].ContainsKey('OCIR_REPOSITORY_NAME')) {
  $obj['variables'].Remove('OCIR_REPOSITORY_NAME')
  Write-Host "  Chave OCIR_REPOSITORY_NAME removida do objeto" -ForegroundColor Green
} else {
  Write-Host "  OCIR_REPOSITORY_NAME nao encontrada" -ForegroundColor Yellow
}

# Adicionar projectReferences obrigatorio
$projRef = New-Object System.Collections.Generic.Dictionary'[string,object]'
$projRef['name'] = 'oci-terraform'
$innerProj = New-Object System.Collections.Generic.Dictionary'[string,object]'
$innerProj['id'] = $projectId
$innerProj['name'] = 'Invista FIDC - Nexus'
$projRef['projectReference'] = $innerProj
$obj['projectReferences'] = @($projRef)

$updatedJson = $serializer.Serialize($obj)

Write-Host "=== 1. PUT oci-terraform sem OCIR_REPOSITORY_NAME ===" -ForegroundColor Cyan
try {
  $result = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups/$vgId`?api-version=7.0" -Method PUT -Headers $h -Body $updatedJson -ErrorAction Stop
  $vars = $result.variables.PSObject.Properties.Name
  if ('OCIR_REPOSITORY_NAME' -in $vars) {
    Write-Host "  AVISO: variavel ainda presente" -ForegroundColor Yellow
  } else {
    Write-Host "  OK - removida. Variaveis: $($vars -join ', ')" -ForegroundColor Green
  }
} catch {
  $errRaw = $_.ErrorDetails.Message
  try { $errMsg = ($errRaw | ConvertFrom-Json).message } catch { $errMsg = $errRaw }
  Write-Host "  ERRO: $errMsg" -ForegroundColor Red
  # Debug: mostrar os primeiros 300 chars do body
  Write-Host "  Body (300 chars): $($updatedJson.Substring(0, [Math]::Min(300, $updatedJson.Length)))"
}

# =====================================================================
# 2. Criar VG ms-parameters-dev
# =====================================================================
Write-Host "`n=== 2. Criando VG ms-parameters-dev ===" -ForegroundColor Cyan

$vgs = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups?api-version=7.0" -Headers $h
$existing = $vgs.value | Where-Object { $_.name -eq 'ms-parameters-dev' }
if ($existing) {
  Write-Host "  Ja existe (ID: $($existing.id))" -ForegroundColor Yellow
} else {
  $newProjRef = @(
    @{
      name = 'ms-parameters-dev'
      projectReference = @{ id = $projectId; name = 'Invista FIDC - Nexus' }
    }
  )
  $newVg = @{
    name      = 'ms-parameters-dev'
    type      = 'Vsts'
    variables = @{
      CLUSTER_NAME            = @{ value = 'NexusCluster';  isSecret = $false }
      LOG_GROUP_NAME          = @{ value = '/ecs/logs';     isSecret = $false }
      TASK_CONTAINER_NAME     = @{ value = 'ms-parameters'; isSecret = $false }
      TASK_FAMILY             = @{ value = 'ms-parameters'; isSecret = $false }
      TASK_EXECUTION_ROLE_ARN = @{ value = '';              isSecret = $true }
      TASK_ROLE_ARN           = @{ value = '';              isSecret = $true }
      LAST_SWAGGER_HASH       = @{ value = '';              isSecret = $false }
    }
    projectReferences = $newProjRef
  } | ConvertTo-Json -Depth 6

  try {
    $created = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups?api-version=7.0" -Method POST -Headers $h -Body $newVg -ErrorAction Stop
    Write-Host "  OK - criado: $($created.name) (ID: $($created.id))" -ForegroundColor Green
  } catch {
    $errRaw = $_.ErrorDetails.Message
    try { $errMsg = ($errRaw | ConvertFrom-Json).message } catch { $errMsg = $errRaw }
    Write-Host "  ERRO: $errMsg" -ForegroundColor Red
  }
}
