<?php
declare(strict_types=1);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/app/session.php';

$checks = [];
$failures = 0;

function qa_check(array &$checks, int &$failures, string $name, bool $condition): void
{
    if (!$condition) {
        $failures++;
    }
    $checks[] = [$condition ? 'PASS' : 'FAIL', $name];
}

qa_check($checks, $failures, 'Period neaktivnosti je 600 sekundi', session_idle_timeout_seconds() === 600);
qa_check($checks, $failures, 'Period upozorenja je 60 sekundi', session_warning_duration_seconds() === 60);
qa_check($checks, $failures, 'Krajnji serverski rok je 660 sekundi', session_hard_timeout_seconds() === 660);
qa_check($checks, $failures, 'Throttling aktivnosti je 60 sekundi', session_activity_throttle_seconds() === 60);

$_SESSION = ['user_id' => 7, 'last_activity' => 1000, 'session_started_at' => 1234567890];
qa_check($checks, $failures, 'Sesija je validna u 659. sekundi', authenticated_session_has_expired(1659) === false);
qa_check($checks, $failures, 'Sesija ističe tačno u 660. sekundi', authenticated_session_has_expired(1660) === true);

$_SERVER = [
    'REQUEST_METHOD' => 'GET',
    'HTTP_ACCEPT' => 'text/html,application/xhtml+xml',
    'HTTP_SEC_FETCH_MODE' => 'navigate',
    'HTTP_SEC_FETCH_DEST' => 'document',
];
qa_check($checks, $failures, 'Top-level navigacija se računa kao aktivnost', request_represents_user_navigation() === true);

$_SERVER = [
    'REQUEST_METHOD' => 'GET',
    'HTTP_ACCEPT' => 'application/json',
    'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest',
    'HTTP_SEC_FETCH_MODE' => 'cors',
    'HTTP_SEC_FETCH_DEST' => 'empty',
];
qa_check($checks, $failures, 'AJAX zahtev se ne računa kao aktivnost', request_represents_user_navigation() === false);

$_SERVER = [
    'REQUEST_METHOD' => 'GET',
    'HTTP_ACCEPT' => 'text/html',
    'HTTP_SEC_PURPOSE' => 'prefetch',
];
qa_check($checks, $failures, 'Prefetch se ne računa kao aktivnost', request_represents_user_navigation() === false);

$_SERVER = [
    'REQUEST_METHOD' => 'POST',
    'HTTP_ACCEPT' => 'text/html',
];
qa_check($checks, $failures, 'Klasično slanje forme se računa kao aktivnost', request_represents_user_navigation() === true);

foreach ($checks as [$status, $name]) {
    echo str_pad($status, 4) . ' | ' . $name . PHP_EOL;
}
echo PHP_EOL . 'UKUPNO: ' . (count($checks) - $failures) . '/' . count($checks) . ' PASS' . PHP_EOL;
exit($failures === 0 ? 0 : 1);
