$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

# GET VG por ID (nao pela lista)
$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
Write-Host "  Variaveis atuais: $($vg.variables.PSObject.Properties.Name -join ', ')"

# Construir novo objeto de variaveis
$newVars = [ordered]@{}
foreach ($prop in $vg.variables.PSObject.Properties) {
  if ($prop.Name -ne 'OCIR_REPOSITORY_NAME') {
    # Preservar isSecret e value
    $entry = @{}
    if ($null -ne $prop.Value.isSecret -and $prop.Value.isSecret -eq $true) {
      $entry['isSecret'] = $true
      # Nao incluir value para secrets (o servidor mantem o valor)
    } else {
      $entry['isSecret'] = $false
      $entry['value'] = if ($null -ne $prop.Value.value) { $prop.Value.value } else { '' }
    }
    $newVars[$prop.Name] = $entry
  }
}
Write-Host "  Variaveis novas ($($newVars.Count)): $($newVars.Keys -join ', ')"

$updateBody = [ordered]@{
  id          = $vg.id
  name        = $vg.name
  type        = $vg.type
  description = $vg.description
  variables   = $newVars
} | ConvertTo-Json -Depth 8

try {
  $result = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups/$vgId`?api-version=7.0" -Method PUT -Headers $h -Body $updateBody -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. Total: $($vars.Count) variaveis" -ForegroundColor Green
  }
} catch {
  $errRaw = $_.ErrorDetails.Message
  try { $errMsg = ($errRaw | ConvertFrom-Json).message } catch { $errMsg = $errRaw }
  Write-Host "  ERRO: $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 {
  # Tentar criar sem projectReferences (endpoint de projeto ja tem contexto)
  $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 }
    }
    projectReferences = @(
      [ordered]@{
        name = 'ms-parameters-dev'
        projectReference = [ordered]@{ id = $projectId }
      }
    )
  } | ConvertTo-Json -Depth 6

  try {
    $created = Invoke-RestMethod -Uri "$base/distributedtask/variablegroups?api-version=7.0" -Method POST -Headers $h -Body $newVgBody -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
    Write-Host "  Body enviado:" -ForegroundColor Gray
    Write-Host $newVgBody
  }
}
