$tokenPath = "$env:USERPROFILE\.ssh\cloudflare-token"
$CF_TOKEN = (Get-Content $tokenPath -Encoding UTF8 -Raw).Trim()
Write-Host "Token len: $($CF_TOKEN.Length)  preview: $($CF_TOKEN.Substring(0,4))..."

$cfh = @{ Authorization = "Bearer $CF_TOKEN"; 'Content-Type' = 'application/json' }

# Zone ID
$zonesResp = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones?name=invista.com.br&per_page=1" -Headers $cfh
if (-not $zonesResp.success) {
  Write-Host "ERRO ao buscar zone: $($zonesResp.errors | ConvertTo-Json)"
  exit 1
}
$zoneId = $zonesResp.result[0].id
Write-Host "Zone ID: $zoneId"

# Buscar record existente para mfe-shell-dev.invista.com.br
$name = "mfe-shell-dev.invista.com.br"
$resp = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records?name=$name&per_page=10" -Headers $cfh
Write-Host "Records existentes para $name :"
$resp.result | ForEach-Object {
  Write-Host "  id=$($_.id) type=$($_.type) content=$($_.content) proxied=$($_.proxied)"
}

# IP do FortiGate1 (ponto de entrada público)
$fortiIP = "136.248.66.216"

if ($resp.result.Count -gt 0) {
  # Atualizar record existente (pegar o primeiro)
  $recordId = $resp.result[0].id
  $body = @{
    type    = "A"
    name    = $name
    content = $fortiIP
    ttl     = 1  # 1 = Auto no Cloudflare
    proxied = $true
  } | ConvertTo-Json -Depth 3

  Write-Host ""
  Write-Host "Atualizando record $recordId para A $fortiIP (proxied)..."
  $updateResp = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records/$recordId" `
    -Method PUT -Headers $cfh -Body $body
  if ($updateResp.success) {
    Write-Host "OK: $($updateResp.result.type) $($updateResp.result.name) -> $($updateResp.result.content) proxied=$($updateResp.result.proxied)"
  } else {
    Write-Host "ERRO: $($updateResp.errors | ConvertTo-Json)"
  }
} else {
  # Criar novo record
  $body = @{
    type    = "A"
    name    = $name
    content = $fortiIP
    ttl     = 1
    proxied = $true
  } | ConvertTo-Json -Depth 3

  Write-Host ""
  Write-Host "Criando A record $name -> $fortiIP (proxied)..."
  $createResp = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records" `
    -Method POST -Headers $cfh -Body $body
  if ($createResp.success) {
    Write-Host "OK: $($createResp.result.type) $($createResp.result.name) -> $($createResp.result.content) proxied=$($createResp.result.proxied)"
  } else {
    Write-Host "ERRO: $($createResp.errors | ConvertTo-Json)"
  }
}
