$p = '19mNqNXIoZ4c3EriFNfzfkgpGNOvLjpOqqZnTFXKnzjxWJ5zURjgJQQJ99CBACAAAAAamI5kAAASAZDOAMPp'
$t = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(':' + $p))
$h = @{ Authorization = 'Basic ' + $t; 'Content-Type' = 'application/json' }
$baseOrg = 'https://dev.azure.com/CN-Squad/_apis'
$projectId = '28c26924-b0a7-485d-b8c2-c86e48377e85'
$vgId = 34

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

# =====================================================================
# 1. Remover OCIR_REPOSITORY_NAME via PUT no endpoint de organizacao
# =====================================================================
Write-Host "=== 1. Removendo OCIR_REPOSITORY_NAME do oci-terraform ===" -ForegroundColor Cyan

$newVars = @{}
$vg.variables.PSObject.Properties | Where-Object { $_.Name -ne 'OCIR_REPOSITORY_NAME' } | ForEach-Object {
  $newVars[$_.Name] = $_.Value
}

$updateBody = @{
  id          = $vg.id
  name        = $vg.name
  type        = $vg.type
  variables   = $newVars
  description = $vg.description
} | ConvertTo-Json -Depth 10

$url = "$baseOrg/distributedtask/variablegroups/$vgId`?projectIds=$projectId`&api-version=7.0"
try {
  $hWithCT = @{ Authorization = 'Basic ' + $t; 'Content-Type' = 'application/json' }
  $result = Invoke-RestMethod -Uri $url -Method PUT -Headers $hWithCT -Body $updateBody -ErrorAction Stop
  $stillHas = $result.variables.PSObject.Properties | Where-Object { $_.Name -eq 'OCIR_REPOSITORY_NAME' }
  if ($stillHas) {
    Write-Host "  AVISO: variavel ainda presente" -ForegroundColor Yellow
  } else {
    Write-Host "  OK - OCIR_REPOSITORY_NAME removido" -ForegroundColor Green
  }
} catch {
  $errMsg = $_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue
  Write-Host "  ERRO: $($errMsg.message)" -ForegroundColor Red
}

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

# Verificar se ja existe
$allVgs = Invoke-RestMethod -Uri "$baseOrg/distributedtask/variablegroups?api-version=7.0" -Headers $h
$existing = $allVgs.value | Where-Object { $_.name -eq 'ms-parameters-dev' }
if ($existing) {
  Write-Host "  Ja existe (ID: $($existing.id))" -ForegroundColor Yellow
} else {
  $newVgBody = @{
    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 }
    }
  } | ConvertTo-Json -Depth 5

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