import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

const control = (action: string) => fetch(`http://127.0.0.1:19689/${action}`).then(r => r.json());
test('Refreshing an issue discards older comment pages and pending requests', WEB, async ({t3, app, screen, browser}) => {
  await control('reset');
  await t3.project('comments-demo', {'.git/config':'[core]\nrepositoryformatversion = 0\nbare = false\n[remote "origin"]\nurl = https://github.com/scenario/comments.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n'});
  await t3.open('/issues');
  await screen.getByText('Refresh race — 201 synthetic comments').tap();
  await screen.getByRole('button', 'Load older comments').tap();
  await screen.getByText('PREVIOUS PAGE — comment 002').waitFor({state:'visible'});
  await screen.getByRole('button', 'Load older comments').tap();
  await screen.getByRole('button', 'Refresh issue', {exact:true}).tap();
  await app.screenshot('refresh-pending');
  await control('release-refresh');
  await screen.getByRole('button', 'Refresh issue', {exact:true}).waitFor({state:'visible'});
  await control('release-older');
  // A round trip through the browser lets both completed RPC responses render.
  await browser.evaluate(async () => { await new Promise(resolve=>setTimeout(resolve,1000)); });
  await browser.evaluate(() => { for(const el of document.querySelectorAll('*')) if(el.scrollHeight>el.clientHeight+200 && el.clientHeight>100) el.scrollTop=0; });
  await app.screenshot('after-refresh');
  await expect(screen.getByText('OLDEST PAGE — comment 001')).not.toBeVisible();
  await expect(screen.getByText('PREVIOUS PAGE — comment 002')).not.toBeVisible();
  await expect(screen.getByText('LATEST PAGE — comment 102')).toBeVisible();
});
