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

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

Write-Host "--- Cloudflare DNS Update (Backend API) ---"
$zonesUrl = "https://api.cloudflare.com/client/v4/zones?name=$domain"
$zonesResponse = Invoke-RestMethod -Uri $zonesUrl -Headers $headers -Method Get
$zoneId = $zonesResponse.result[0].id

$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    = "api-dev"
    content = $redbullIp
    ttl     = 1
    proxied = $false
} | ConvertTo-Json

if ($recordId) {
    Invoke-RestMethod -Uri "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records/$recordId" -Headers $headers -Method Put -Body $body
    Write-Host "✅ api-dev record updated."
} else {
    Invoke-RestMethod -Uri "https://api.cloudflare.com/client/v4/zones/$zoneId/dns_records" -Headers $headers -Method Post -Body $body
    Write-Host "➕ api-dev record created."
}
