/**
 * Cloudflare DNS management for forum subdomains.
 */

const CF_API = "https://api.cloudflare.com/client/v4";

function headers(): Record<string, string> {
	const token = process.env.CLOUDFLARE_API_TOKEN;
	if (!token) throw new Error("CLOUDFLARE_API_TOKEN not set");
	return {
		Authorization: `Bearer ${token}`,
		"Content-Type": "application/json",
	};
}

export async function createDNSRecord(
	subdomain: string,
	ip: string,
): Promise<{ recordId: string } | null> {
	const zoneId = process.env.CLOUDFLARE_FORUM_ZONE_ID;
	if (!zoneId) throw new Error("CLOUDFLARE_FORUM_ZONE_ID not set");

	const res = await fetch(`${CF_API}/zones/${zoneId}/dns_records`, {
		method: "POST",
		headers: headers(),
		body: JSON.stringify({
			type: "A",
			name: `${subdomain}.rforum.online`,
			content: ip,
			ttl: 300,
			proxied: false,
		}),
	});

	if (!res.ok) {
		console.error("[Forum DNS] Failed to create record:", await res.text());
		return null;
	}

	const data = await res.json();
	return { recordId: data.result.id };
}

export async function deleteDNSRecord(recordId: string): Promise<boolean> {
	const zoneId = process.env.CLOUDFLARE_FORUM_ZONE_ID;
	if (!zoneId) return false;

	const res = await fetch(`${CF_API}/zones/${zoneId}/dns_records/${recordId}`, {
		method: "DELETE",
		headers: headers(),
	});
	return res.ok;
}
