<?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);

$runId = 0;
$templateKeys = ['__QUEUE_RUN_TEST_OK__', '__QUEUE_RUN_TEST_FAIL__'];

try {
    $conn->query("INSERT INTO message_queue_runs
      (status,test_phone,confirmation_required,test_sent,total_count,started_at)
      VALUES ('RUNNING','0000000000',0,1,2,NOW())");
    $runId = (int)$conn->insert_id;

    $conn->query("INSERT INTO message_outbox
      (template_key,to_phone,channel,body,status,run_id)
      VALUES
      ('{$templateKeys[0]}','0000000001','sms','test success','QUEUED',{$runId}),
      ('{$templateKeys[1]}','0000000002','sms','test failure','QUEUED',{$runId})");

    $result = messages_queue_process_step(
        $conn,
        $runId,
        10,
        static function (mysqli $db, array $row): array {
            if (($row['template_key'] ?? '') === '__QUEUE_RUN_TEST_OK__') {
                return ['ok'=>true, 'message_id'=>'fake-success'];
            }
            return ['ok'=>false, 'error'=>'fake-failure'];
        }
    );

    $run = $result['run'] ?? [];
    $passed = !empty($result['ok'])
        && ($run['status'] ?? '') === 'COMPLETED'
        && (int)($run['sent'] ?? -1) === 1
        && (int)($run['failed'] ?? -1) === 1
        && (int)($run['processed'] ?? -1) === 2
        && (int)($run['percent'] ?? -1) === 100;

    if (!$passed) {
        fwrite(STDERR, "FAIL " . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL);
        exit(1);
    }

    echo "PASS persistent queue progress and retry accounting" . PHP_EOL;
} finally {
    if ($runId > 0) {
        $conn->query("DELETE FROM message_logs WHERE template_key IN ('{$templateKeys[0]}','{$templateKeys[1]}')");
        $conn->query("DELETE FROM message_outbox WHERE run_id={$runId}");
        $conn->query("DELETE FROM message_queue_runs WHERE id={$runId}");
    }
}
