<?php
/**
 * Pure, server-authoritative validation + normalization for DNS record input.
 * No I/O — safe to unit test locally and to reuse from api/dns-ajax.php.
 */

const DNS_RECORD_TYPES = ['A','AAAA','CNAME','MX','TXT','NS','PTR','SRV','CAA','SSHFP','TLSA','DS','DNSKEY','RRSIG','NSEC','NSEC3'];
const DNS_PRIORITY_TYPES = ['MX','SRV'];

/** Clamp a TTL into PowerDNS-sane bounds [300, 86400]. */
function dns_record_normalize_ttl($ttl): int {
    $ttl = (int) $ttl;
    if ($ttl < 300) { return 300; }
    if ($ttl > 86400) { return 86400; }
    return $ttl;
}

/** Wrap TXT content in double quotes if not already quoted. */
function dns_record_quote_txt(string $content): string {
    return preg_match('/^".*"$/s', $content) ? $content : '"' . $content . '"';
}

/** Build the PowerDNS content line for a type (prefixes MX/SRV priority). */
function dns_record_content_line(string $type, string $content, ?int $priority): string {
    $type = strtoupper($type);
    // MX and SRV carry their priority as the leading field of the content line.
    // The UI splits it out for editing; recombine it here on the way back in.
    if (in_array($type, ['MX', 'SRV'], true) && $priority !== null) {
        return $priority . ' ' . $content;
    }
    return $content;
}

/**
 * Validate a record submission.
 * @param array $r ['type','name','content','ttl','priority'?]
 * @return array ['ok'=>bool, 'error'=>?string]
 */
function dns_record_validate(array $r): array {
    $type = strtoupper(trim($r['type'] ?? ''));
    if (!in_array($type, DNS_RECORD_TYPES, true)) {
        return ['ok' => false, 'error' => 'Invalid record type'];
    }
    if (trim((string)($r['name'] ?? '')) === '') {
        return ['ok' => false, 'error' => 'Name is required'];
    }
    if (trim((string)($r['content'] ?? '')) === '') {
        return ['ok' => false, 'error' => 'Content is required'];
    }
    if (in_array($type, DNS_PRIORITY_TYPES, true)) {
        $prio = $r['priority'] ?? null;
        if ($prio === null || $prio === '' || !is_numeric($prio) || (int)$prio < 0 || (int)$prio > 65535) {
            return ['ok' => false, 'error' => $type . ' records require a numeric priority (0–65535)'];
        }
    }
    return ['ok' => true, 'error' => null];
}
