<?php
declare(strict_types=1);

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

$conn = ensure_db(true);
ensure_message_queue_tables($conn);

$campaignId = 0;
$templateKey = '__CAMPAIGN_LIFECYCLE_TEST__';
$templateEsc = $conn->real_escape_string($templateKey);

try {
    $conn->query("INSERT INTO message_campaigns
      (title,template_key,channel,status)
      VALUES ('Campaign lifecycle test','{$templateEsc}','sms','QUEUED')");
    $campaignId = (int)$conn->insert_id;

    $conn->query("INSERT INTO message_outbox
      (campaign_id,template_key,to_phone,channel,body,status)
      VALUES
      ({$campaignId},'{$templateEsc}','0000000101','sms','pending test','QUEUED'),
      ({$campaignId},'{$templateEsc}','0000000102','sms','sent test','SENT')");

    $paused = messages_campaign_pause($conn, $campaignId);
    $pausedRs = $conn->query("SELECT status FROM message_outbox
      WHERE campaign_id={$campaignId} AND to_phone='0000000101' LIMIT 1");
    $pausedRow = $pausedRs && $pausedRs->num_rows ? $pausedRs->fetch_assoc() : [];
    if (empty($paused['ok']) || ($pausedRow['status'] ?? '') !== 'PAUSED') {
        throw new RuntimeException('Campaign pause did not preserve the pending row as PAUSED.');
    }

    $resumed = messages_campaign_resume($conn, $campaignId);
    $resumedRs = $conn->query("SELECT status FROM message_outbox
      WHERE campaign_id={$campaignId} AND to_phone='0000000101' LIMIT 1");
    $resumedRow = $resumedRs && $resumedRs->num_rows ? $resumedRs->fetch_assoc() : [];
    if (empty($resumed['ok']) || ($resumedRow['status'] ?? '') !== 'QUEUED') {
        throw new RuntimeException('Campaign resume did not restore the pending row to QUEUED.');
    }

    $deleted = messages_campaign_delete($conn, $campaignId);
    $campaignRs = $conn->query("SELECT COUNT(*) AS c FROM message_campaigns WHERE id={$campaignId}");
    $campaignCount = (int)(($campaignRs ? $campaignRs->fetch_assoc() : [])['c'] ?? -1);
    $pendingRs = $conn->query("SELECT COUNT(*) AS c FROM message_outbox
      WHERE template_key='{$templateEsc}' AND to_phone='0000000101'");
    $pendingCount = (int)(($pendingRs ? $pendingRs->fetch_assoc() : [])['c'] ?? -1);
    $sentRs = $conn->query("SELECT campaign_id,status FROM message_outbox
      WHERE template_key='{$templateEsc}' AND to_phone='0000000102' LIMIT 1");
    $sentRow = $sentRs && $sentRs->num_rows ? $sentRs->fetch_assoc() : [];

    $passed = !empty($deleted['ok'])
        && $campaignCount === 0
        && $pendingCount === 0
        && array_key_exists('campaign_id', $sentRow)
        && $sentRow['campaign_id'] === null
        && ($sentRow['status'] ?? '') === 'SENT';
    if (!$passed) throw new RuntimeException('Campaign delete did not preserve delivered history correctly.');

    echo "PASS campaign pause, resume, and history-preserving delete" . PHP_EOL;
} catch (Throwable $e) {
    fwrite(STDERR, 'FAIL ' . $e->getMessage() . PHP_EOL);
    exit(1);
} finally {
    $conn->query("DELETE FROM message_outbox WHERE template_key='{$templateEsc}'");
    $conn->query("DELETE FROM message_campaigns WHERE template_key='{$templateEsc}'");
}
