<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/db_bootstrap.php';
ensure_db(true);
require_once dirname(__DIR__) . '/subscriber_contracts_lib.php';

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) throw new RuntimeException('Database connection is unavailable.');

$default = sc_default_template($conn);
if (!$default) throw new RuntimeException('No active default contract template is available.');

$resolved = sc_resolve_contract_template($conn, PHP_INT_MAX);
if (!$resolved || (int)$resolved['id'] !== (int)$default['id']) {
    throw new RuntimeException('A stale template id did not fall back to the approved default.');
}

$selected = sc_resolve_contract_template($conn, (int)$default['id']);
if (!$selected || (int)$selected['id'] !== (int)$default['id']) {
    throw new RuntimeException('A valid selected template was not preserved.');
}

echo "subscriber_contract_template_resolution_test: OK\n";
