<?php
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/MraEisCompliance.php';

$db = new Database();
$conn = $db->getConnection();
new MraEisCompliance($conn); // Apply the class's compatibility schema checks before the test transaction.

$terminalId = (int)$conn->query(
    'SELECT terminal_local_id FROM mra_eis_configurations ORDER BY terminal_local_id LIMIT 1'
)->fetchColumn();
if ($terminalId <= 0) {
    fwrite(STDERR, "SKIP: no stored MRA EIS terminal configuration.\n");
    exit(0);
}

$failures = [];
$check = static function ($condition, $message) use (&$failures) {
    if (!$condition) {
        $failures[] = $message;
    }
};
$service = new MraEisOfflineThreshold($conn);
$conn->beginTransaction();
try {
    $conn->prepare(
        "UPDATE mra_eis_configurations SET offline_time_threshold_hours = 2, "
        . "offline_started_at = NULL, eis_connection_status = 'online' WHERE terminal_local_id = :id"
    )->execute([':id' => $terminalId]);

    $first = $service->startOfflinePeriod($terminalId, 1, 'Automated connectivity failure fixture.');
    $second = $service->startOfflinePeriod($terminalId, 1, 'Repeated failure fixture.');
    $check($first['connection_status'] === 'offline', 'First connectivity failure must mark the terminal offline.');
    $check($first['offline_started_at'] === $second['offline_started_at'], 'Repeated failures must not reset offline_started_at.');
    $check(!$service->assertOfflineSaleAllowed($terminalId, 1, 'test-before-expiry')['expired'], 'Sale must be allowed before expiry.');

    $conn->prepare(
        'UPDATE mra_eis_configurations SET offline_started_at = UTC_TIMESTAMP() - INTERVAL 2 HOUR WHERE terminal_local_id = :id'
    )->execute([':id' => $terminalId]);
    $blockedAtExpiry = false;
    try {
        $service->assertOfflineSaleAllowed($terminalId, 1, 'test-at-expiry');
    } catch (RuntimeException $e) {
        $blockedAtExpiry = strpos($e->getMessage(), 'offline time limit has expired') !== false;
    }
    $check($blockedAtExpiry, 'Sale must be blocked exactly at or after expiry.');

    $conn->prepare(
        'UPDATE mra_eis_configurations SET offline_time_threshold_hours = 0 WHERE terminal_local_id = :id'
    )->execute([':id' => $terminalId]);
    $invalidBlocked = false;
    try {
        $service->assertOfflineSaleAllowed($terminalId, 1, 'test-invalid-threshold');
    } catch (RuntimeException $e) {
        $invalidBlocked = true;
    }
    $check($invalidBlocked, 'Invalid threshold must block an offline sale.');
    $check($service->getStatus(999999999) === null, 'Missing terminal configuration must not produce an offline window.');

    $service->markTerminalOnline($terminalId, 1);
    $online = $service->getStatus($terminalId);
    $check($online['connection_status'] === 'online', 'Successful communication must restore online status.');
    $check($online['offline_started_at'] === null, 'Successful communication must clear the offline start.');
} finally {
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
}

if ($failures) {
    foreach ($failures as $failure) {
        fwrite(STDERR, 'FAIL: ' . $failure . PHP_EOL);
    }
    exit(1);
}

echo 'PASS: MRA EIS offline threshold database integration checks' . PHP_EOL;
