import {readFileSync, writeFileSync} from 'node:fs';
import {setTimeout as delay} from 'node:timers/promises';
import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

test('Opening an uncached Bitbucket pull request during a background rate-limit pause', WEB, async ({t3,app,screen}) => {
  const capture = async (label: string) => {
    let previous = await app.screenshot(label + '-settling');
    for (let attempt = 0; attempt < 5; attempt++) {
      await delay(500);
      const current = await app.screenshot(label);
      if (readFileSync(previous).equals(readFileSync(current))) return;
      previous = current;
    }
    throw new Error('Capture did not settle');
  };
  await fetch('http://127.0.0.1:18995/reset');
  await t3.project('Bitbucket demo', {'.git/config': '[remote \"origin\"]\n url = https://bitbucket.org/demo/web.git\n'});
  await t3.open();
  await screen.getByText('Bitbucket demo', {exact:true}).first().waitFor({state:'visible'});
  await app.open('/pull-requests?repository=demo%2Fweb&number=1&host=bitbucket.org&sort=updated');
  await screen.getByText(/Bitbucket returned HTTP 429|requests to bitbucket.org are paused/, {exact:false}).first().waitFor({state:'visible'});
  await capture('host-paused');
  await app.open('/pull-requests?repository=demo%2Fweb&number=2&host=bitbucket.org&sort=updated');
  await screen.getByText(/paused until|Detail accepted during the background pause/).first().waitFor({state:'visible'});
  await capture('opened-during-pause');
  if (process.env.HOST_REQUEST_LOG) writeFileSync(process.env.HOST_REQUEST_LOG, JSON.stringify(await (await fetch('http://127.0.0.1:18995/requests')).json(), null, 2));
  await expect(screen.getByText('Detail accepted during the background pause.',{exact:false})).toBeVisible();
  await screen.getByRole('button','Timeline').tap();
  await screen.getByRole('button', /^1 comment 1 author/).tap();
  await expect(screen.getByText('Activity accepted during the background pause.',{exact:false,visible:true})).toBeVisible();
  await capture('activity-loaded');
});
