$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,6))..."

$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"
Write-Host ""

# Records
foreach ($sub in @('crivo-dev', 'mfe-user-dev', 'mfe-shell-dev')) {
  $name = "$sub.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 "=== $name ==="
  if ($resp.result.Count -eq 0) {
    Write-Host "  (sem record)"
  } else {
    $resp.result | ForEach-Object {
      Write-Host "  type=$($_.type)  content=$($_.content)  proxied=$($_.proxied)"
    }
  }
  Write-Host ""
}

# Tunnels
Write-Host "=== Cloudflare Tunnels (via zone) ==="
$accResp = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId" -Headers $cfh
$accountId = $accResp.result.account.id
Write-Host "Account ID: $accountId"
if ($accountId) {
  $tuns = Invoke-RestMethod "https://api.cloudflare.com/client/v4/accounts/$accountId/cfd_tunnel?status=active&per_page=10" -Headers $cfh
  if ($tuns.result.Count -eq 0) {
    Write-Host "  (nenhum tunnel ativo)"
  } else {
    $tuns.result | ForEach-Object { Write-Host "  tunnel: $($_.name)  id=$($_.id)" }
  }
}
