import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';

const root = new URL('../', import.meta.url);

test('browser savegames are buffered before one OPFS write', async () => {
  const [patch, wasmBuild, nativeBuild, sourceOffer, e2e] = await Promise.all([
    readFile(new URL('port/native/patches/0016-buffer-browser-savegame-writes.patch', root), 'utf8'),
    readFile(new URL('tools/build-wasm.sh', root), 'utf8'),
    readFile(new URL('tools/build-native.sh', root), 'utf8'),
    readFile(new URL('tools/stage-source-offer.sh', root), 'utf8'),
    readFile(new URL('tools/e2e-full.mjs', root), 'utf8')
  ]);

  assert.match(patch, /#if defined\( __EMSCRIPTEN__ \)[\s\S]*idFile_Memory \*bufferedGameFile/);
  assert.match(patch, /SetGranularity\( 8 \* 1024 \* 1024 \)/);
  assert.equal((patch.match(/permanentGameFile->Write\(/g) || []).length, 1);
  assert.match(patch, /Browser save staged %d bytes in one filesystem write/);
  assert.match(patch, /Session_ValidateStagedSaveGameHeader/);
  assert.match(patch, /Session_RemoveStagedSaveFiles/);

  for (const build of [wasmBuild, nativeBuild, sourceOffer]) {
    assert.match(build, /0016-buffer-browser-savegame-writes\.patch/);
  }
  assert.match(e2e, /Browser save staged/);
});
