<?php
require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/messages_lib.php';

$conn = ensure_db(true);
$all = messages_campaign_eligible_targets($conn, ['audience'=>'all']);
if (count($all) < 2) {
    echo "SKIP selected-subscriber scope requires two subscribers with valid phone numbers" . PHP_EOL;
    exit(0);
}

$ids = [(int)$all[0]['id'], (int)$all[1]['id']];
$filters = messages_campaign_normalize_filters([
    'audience'=>'all',
    'subscriber_ids'=>[$ids[0], (string)$ids[1], $ids[0], 0, -1],
]);
if ($filters['subscriber_ids'] !== $ids) {
    throw new RuntimeException('Selected subscriber IDs were not normalized and deduplicated.');
}

$selected = messages_campaign_eligible_targets($conn, $filters);
$actualIds = array_map(static fn(array $row): int => (int)$row['id'], $selected);
sort($ids);
sort($actualIds);
if ($actualIds !== $ids) {
    throw new RuntimeException('Campaign eligibility escaped the explicitly selected subscriber IDs.');
}

echo "PASS message audience is restricted to explicitly selected subscribers" . PHP_EOL;
