<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

require_once __DIR__ . '/../src/storage.php';

$options = getopt('', ['worker::', 'file::']);
$worker = isset($options['worker']) ? (int) $options['worker'] : null;
$file = (string) ($options['file'] ?? (sys_get_temp_dir() . '/darex_json_storage_test.json'));

if ($worker !== null) {
    for ($index = 0; $index < 100; $index++) {
        $key = $worker . ':' . $index;
        updateJsonFile($file, ['items' => []], static function (array $data) use ($key): array {
            $data['items'][$key] = true;

            return $data;
        });
    }
    exit(0);
}

@unlink($file);
@unlink($file . '.lock');
$processes = [];
for ($workerId = 0; $workerId < 8; $workerId++) {
    $command = escapeshellarg(PHP_BINARY)
        . ' ' . escapeshellarg(__FILE__)
        . ' --worker=' . $workerId
        . ' --file=' . escapeshellarg($file);
    $process = proc_open($command, [], $pipes);
    if (!is_resource($process)) {
        throw new RuntimeException('Cannot start JSON storage test worker.');
    }
    $processes[] = $process;
}

foreach ($processes as $process) {
    if (proc_close($process) !== 0) {
        throw new RuntimeException('JSON storage test worker failed.');
    }
}

$data = readJsonFile($file, ['items' => []]);
$count = count((array) ($data['items'] ?? []));
$ok = $count === 800;

echo json_encode([
    'ok' => $ok,
    'expected_items' => 800,
    'actual_items' => $count,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;

@unlink($file);
@unlink($file . '.lock');
exit($ok ? 0 : 1);
