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

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

Write-Host "--- Cloudflare DNS Update ---"
Write-Host "Target: $recordName -> $redbullIp"

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

if (-not $zoneId) {
    Write-Host "❌ Zone $domain 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
$record = $dnsResponse.result[0]
$recordId = $record.id

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

if ($recordId) {
    Write-Host "🔄 Updating existing record $recordId (Current IP: $($record.content))..."
    $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
