<?php
declare(strict_types=1);

define('BOT_TEST_MODE', true);
require_once __DIR__ . '/../bot.php';

function testResult(string $label, bool $ok, string $detail = ''): void {
    $status = $ok ? 'PASS' : 'FAIL';
    echo "[{$status}] {$label}";
    if ($detail !== '') {
        echo " - {$detail}";
    }
    echo PHP_EOL;
}

$allOk = true;

// 1) reaction add => must be ignored
$reactionPayload = [
    'object' => 'page',
    'entry' => [[
        'id' => '870202386183504',
        'changes' => [[
            'field' => 'feed',
            'value' => [
                'item' => 'reaction',
                'verb' => 'add',
                'post_id' => '870202386183504_122114203887169432',
                'from' => ['id' => 'u1', 'name' => 'User One'],
            ],
        ]],
    ]],
];
$reactionEvent = extractWebhookMessage($reactionPayload);
$ok = ($reactionEvent === null);
$allOk = $allOk && $ok;
testResult('reaction add is ignored', $ok);

// 2) user comment add => must be extracted as comment
$commentPayload = [
    'object' => 'page',
    'entry' => [[
        'id' => '870202386183504',
        'changes' => [[
            'field' => 'feed',
            'value' => [
                'item' => 'comment',
                'verb' => 'add',
                'comment_id' => '122101498647169432_1585806832666912',
                'post_id' => '870202386183504_122101498647169432',
                'message' => 'ممتاز',
                'from' => ['id' => '26092268700409725', 'name' => 'Ahmed Magdy'],
            ],
        ]],
    ]],
];
$commentEvent = extractWebhookMessage($commentPayload);
$ok = is_array($commentEvent)
    && ($commentEvent['type'] ?? '') === 'comment'
    && ($commentEvent['comment_id'] ?? '') === '122101498647169432_1585806832666912'
    && ($commentEvent['page_id'] ?? '') === '870202386183504';
$allOk = $allOk && $ok;
testResult('comment add extracted', $ok);

// 3) page self-comment => extractor returns event, handler guard should ignore
$selfCommentPayload = [
    'object' => 'page',
    'entry' => [[
        'id' => '870202386183504',
        'changes' => [[
            'field' => 'feed',
            'value' => [
                'item' => 'comment',
                'verb' => 'add',
                'comment_id' => 'c_self_1',
                'message' => 'رد من الصفحة',
                'from' => ['id' => '870202386183504', 'name' => 'Page Admin'],
            ],
        ]],
    ]],
];
$selfCommentEvent = extractWebhookMessage($selfCommentPayload);
$ok = is_array($selfCommentEvent)
    && ($selfCommentEvent['type'] ?? '') === 'comment'
    && (($selfCommentEvent['from_id'] ?? '') === ($selfCommentEvent['page_id'] ?? ''));
$allOk = $allOk && $ok;
testResult('self comment recognized for handler ignore', $ok);

if (!$allOk) {
    exit(1);
}

