$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

$vg = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups/$vgId`?api-version=7.0" -Headers $h

# =====================================================================
# 1. Remover OCIR_REPOSITORY_NAME
# =====================================================================
Write-Host "=== 1. Removendo OCIR_REPOSITORY_NAME do oci-terraform ===" -ForegroundColor Cyan

$newVars = [ordered]@{}
foreach ($prop in $vg.variables.PSObject.Properties) {
  if ($prop.Name -ne 'OCIR_REPOSITORY_NAME') {
    $entry = @{}
    if ($prop.Value.isSecret -eq $true) {
      $entry['isSecret'] = $true
    } else {
      $entry['isSecret'] = $false
      $entry['value'] = if ($null -ne $prop.Value.value) { [string]$prop.Value.value } else { '' }
    }
    $newVars[$prop.Name] = $entry
  }
}

# Tentar diferentes versoes da API
foreach ($apiVer in @('7.1-preview.2', '7.0', '6.0', '5.1-preview.1')) {
  $updateBody = [ordered]@{
    id        = [int]$vg.id
    name      = [string]$vg.name
    type      = [string]$vg.type
    variables = $newVars
  } | ConvertTo-Json -Depth 8

  $url = "$base/distributedtask/variablegroups/$vgId`?api-version=$apiVer"
  Write-Host "  Tentando api-version=$apiVer ..."
  try {
    $result = Invoke-RestMethod -Uri $url -Method PUT -Headers $h -Body $updateBody -ErrorAction Stop
    $vars = $result.variables.PSObject.Properties.Name
    if ('OCIR_REPOSITORY_NAME' -in $vars) {
      Write-Host "  AVISO: ainda presente" -ForegroundColor Yellow
    } else {
      Write-Host "  OK com api-version=$apiVer" -ForegroundColor Green
    }
    break
  } catch {
    $errRaw = $_.ErrorDetails.Message
    try { $errMsg = ($errRaw | ConvertFrom-Json).message } catch { $errMsg = $errRaw }
    Write-Host "  ERRO ($apiVer): $errMsg" -ForegroundColor Red
  }
}

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

$vgsCheck = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups?api-version=7.0" -Headers $h
$existing = $vgsCheck.value | Where-Object { $_.name -eq 'ms-parameters-dev' }
if ($existing) {
  Write-Host "  Ja existe (ID: $($existing.id))" -ForegroundColor Yellow
} else {
  foreach ($apiVer in @('7.1-preview.2', '7.0', '6.0', '5.1-preview.1')) {
    $newVgBody = [ordered]@{
      name      = 'ms-parameters-dev'
      type      = 'Vsts'
      variables = [ordered]@{
        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 }
      }
    } | ConvertTo-Json -Depth 6

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