#!/usr/bin/env php
<?php
require_once(__DIR__ . '/../web-files/libs/dns_rrset.php');

$ok = true;
function check($label, $got, $expected) {
    global $ok;
    $g = json_encode($got); $e = json_encode($expected);
    if ($g !== $e) { $ok = false; fprintf(STDERR, "FAIL %s: got %s expected %s\n", $label, $g, $e); }
}

// add: appends, dedups, preserves order
check('add-new',    dns_rrset_apply(['10 a.example.com.'], 'add', null, '20 b.example.com.'),
                    ['10 a.example.com.', '20 b.example.com.']);
check('add-dup',    dns_rrset_apply(['10 a.example.com.'], 'add', null, '10 a.example.com.'),
                    ['10 a.example.com.']);

// edit: replaces the target line in place, leaves siblings untouched
check('edit-one',   dns_rrset_apply(['10 a.example.com.', '20 b.example.com.'], 'edit', '20 b.example.com.', '30 b.example.com.'),
                    ['10 a.example.com.', '30 b.example.com.']);
// edit when target missing -> appends (defensive, never silently drops the user's new value)
check('edit-missing', dns_rrset_apply(['10 a.example.com.'], 'edit', '99 gone.example.com.', '30 b.example.com.'),
                    ['10 a.example.com.', '30 b.example.com.']);

// delete: removes only the target line
check('delete-one', dns_rrset_apply(['10 a.example.com.', '20 b.example.com.'], 'delete', '10 a.example.com.', null),
                    ['20 b.example.com.']);
check('delete-last', dns_rrset_apply(['10 a.example.com.'], 'delete', '10 a.example.com.', null),
                    []);

function checkThrows($label, $fn) {
    global $ok;
    try { $fn(); $ok = false; fprintf(STDERR, "FAIL %s: expected exception, none thrown\n", $label); }
    catch (\InvalidArgumentException $e) { /* expected */ }
}
checkThrows('unknown-op', fn() => dns_rrset_apply(['10 a.example.com.'], 'del', '10 a.example.com.', null));
checkThrows('edit-null',  fn() => dns_rrset_apply(['10 a.example.com.'], 'edit', '10 a.example.com.', null));

echo $ok ? "dns_rrset OK\n" : "dns_rrset FAIL\n";
exit($ok ? 0 : 1);
