$tokenRede5 = '5dcfd89a9d4ec330dede0d4074a518f26818e'
$emailRede5 = 'yamamoto@rede5.com.br'
$redbullIp = '185.194.141.70'
$recordName = 'projetos.rede5.com.br'

$headers = @{
    "X-Auth-Email" = $emailRede5
    "X-Auth-Key"   = $tokenRede5
    "Content-Type" = "application/json"
}

# 1. Get Zone ID for rede5.com.br
$zonesUrl = "https://api.cloudflare.com/client/v4/zones?name=rede5.com.br"
$zonesResponse = Invoke-RestMethod -Uri $zonesUrl -Headers $headers -Method Get
$zoneId = $zonesResponse.result[0].id

if (-not $zoneId) {
    Write-Host "Zone rede5.com.br not found."
    exit
}
Write-Host "Found Zone ID: $zoneId"

# 2. Check if record already exists
$dnsUrl = "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records?name=$recordName"
$dnsResponse = Invoke-RestMethod -Uri $dnsUrl -Headers $headers -Method Get
$recordId = $dnsResponse.result[0].id

$body = @{
    type    = "A"
    name    = "projetos"
    content = $redbullIp
    ttl     = 1
    proxied = $false
} | ConvertTo-Json

if ($recordId) {
    Write-Host "Updating existing record $recordId..."
    $updateUrl = "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records/$recordId"
    $response = Invoke-RestMethod -Uri $updateUrl -Headers $headers -Method Put -Body $body
    Write-Host "Record updated successfully."
}
else {
    Write-Host "Creating new record..."
    $createUrl = "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records"
    $response = Invoke-RestMethod -Uri $createUrl -Headers $headers -Method Post -Body $body
    Write-Host "Record created successfully."
}
$response.result | Select-Object name, content, proxied | Format-Table -AutoSize
