$email = 'tiago.ribeiro@inventcloud.com.br'
$key = '7ae5565ab2dcdfdfdd66efb1105e27d18d186'
$h = @{ 'X-Auth-Email' = $email; 'X-Auth-Key' = $key; 'Content-Type' = 'application/json' }

$zoneName = 'invista.com.br'
$recordName = 'mfe-shell-dev-oci.invista.com.br'
$gwHostname = 'bjlibdhd5wqhf7p3ua4pgv3zly.apigateway.sa-saopaulo-1.oci.customer-oci.com'

# Buscar Zone ID
$zones = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones?name=$zoneName" -Headers $h
$zoneId = $zones.result[0].id
Write-Host "Zone ID: $zoneId"

# Buscar todos os records existentes para o subdomain
$existing = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records?name=$recordName" -Headers $h
Write-Host "Records existentes: $($existing.result.Count)"
$existing.result | ForEach-Object { Write-Host "  $($_.type) $($_.name) -> $($_.content)" }

# Deletar records existentes (A record → FortiGate)
foreach ($rec in $existing.result) {
    Write-Host "Deletando $($rec.id)..."
    $del = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records/$($rec.id)" `
        -Method DELETE -Headers $h
    Write-Host "  Deleted: $($del.success)"
}

# Criar CNAME proxied → OCI API Gateway público
$payload = @{
    type    = 'CNAME'
    name    = $recordName
    content = $gwHostname
    proxied = $true
    ttl     = 1
} | ConvertTo-Json

$result = Invoke-RestMethod "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records" `
    -Method POST -Headers $h -Body $payload

if ($result.success) {
    Write-Host "DNS criado: $recordName -> $gwHostname (CNAME proxied)"
} else {
    Write-Host "ERRO:"
    $result | ConvertTo-Json | Write-Host
}
