<% if(testingFramework == 'node') { %>
import {before, beforeEach, after, afterEach} from 'node:test';
<% } %>
import * as puppeteer from 'puppeteer';

const baseUrl = '<%= baseUrl %>';
let browser: puppeteer.Browser;
let page: puppeteer.Page;

export function setupBrowserHooks(): void {
<% if(testingFramework == 'jasmine' || testingFramework == 'jest') { %>
  beforeAll(async () => {
    browser = await puppeteer.launch({
      headless: 'new'
    });
  });
<% } %><% if(testingFramework == 'mocha' || testingFramework == 'node') { %>
  before(async () => {
    browser = await puppeteer.launch();
  });
<% } %>

  beforeEach(async () => {
    page = await browser.newPage();
    await page.goto(baseUrl);
  });

  afterEach(async () => {
    await page.close();
  });

<% if(testingFramework == 'jasmine' || testingFramework == 'jest') { %>
  afterAll(async () => {
    await browser.close();
  });
<% } %><% if(testingFramework == 'mocha' || testingFramework == 'node') { %>
  after(async () => {
    await browser.close();
  });
<% } %>
}

export function getBrowserState(): {
  browser: puppeteer.Browser;
  page: puppeteer.Page;
  baseUrl: string;
} {
  if (!browser) {
    throw new Error(
      'No browser state found! Ensure `setupBrowserHooks()` is called.'
    );
  }
  return {
    browser,
    page,
    baseUrl,
  };
}
