/// <reference lib="dom" />
import { spawn, execFileSync } from 'node:child_process';
import { mkdir, symlink } from 'node:fs/promises';
import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

test('Edits to a pending first message stay unsent after slow storage replies', WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project('slowdemo');
  await t3.thread({ project, title: 'Earlier work', messages: ['first'] });
  const mount = `${project}/slow-storage`;
  await mkdir(mount);
  const disk = spawn('python3', [process.env.SLOW_STORAGE_DRIVER!, mount], { stdio: ['ignore', 'pipe', 'pipe'] });
  await new Promise<void>((resolve, reject) => {
    disk.stdout.on('data', data => { if (String(data).includes('READY')) resolve(); });
    disk.once('exit', code => reject(new Error(`Slow filesystem exited ${code}`)));
  });
  await symlink('slow-storage/t3.json', `${project}/t3.json`);
  try {
    await browser.addInitScript(() => {
      const requested = Promise.withResolvers<void>();
      const replied = Promise.withResolvers<void>();
      (window as any).slowStorage = { requested: requested.promise, replied: replied.promise };
      const original = WebSocket.prototype.send;
      WebSocket.prototype.send = function(data) {
        if (typeof data === 'string') {
          for (const frame of [JSON.parse(data)].flat()) {
            if (frame.tag === 'projects.readFile' && frame.payload?.relativePath === 't3.json') {
              this.addEventListener('message', event => {
                if ([JSON.parse(String(event.data))].flat().some(item => item._tag === 'Exit' && String(item.requestId) === String(frame.id))) replied.resolve();
              });
              requested.resolve();
            }
          }
        }
        return original.call(this, data);
      };
    });
    await t3.open();
    await browser.evaluate(async () => { await (window as any).slowStorage.requested; return null; });
    const composer = screen.getByRole('textbox');
    await composer.fill('First prompt');
    await app.screenshot('first-prompt-before-enter');
    await composer.press('Enter');
    await composer.fill('Unsubmitted replacement');
    await app.screenshot('replacement-typed-while-storage-pending');
    await browser.evaluate(async () => { await (window as any).slowStorage.replied; return null; });
    try {
      await expect(composer).toHaveText('Unsubmitted replacement');
      await expect(screen.getByText('Draft changed while preparing this message. Review it and send again.')).toBeVisible();
    } finally {
      await app.screenshot('after-slow-storage-replies');
    }
  } finally {
    execFileSync('fusermount3', ['-uz', mount]);
    disk.kill('SIGTERM');
  }
});
