import {
  type Drupal,
  type DrupalSite,
  isolatedPerTest as isolatedPerTestBase,
  parallelWorker as parallelWorkerBase,
} from '@drupal/playwright';
import type { Browser, Page } from '@playwright/test';

import { Canvas } from '../objects/Canvas.js';
import { Conductor } from '../objects/Conductor.js';
import { setupSite } from '../setup.js';

export const isolatedPerTest = isolatedPerTestBase.extend<
  { canvas: Canvas; conductor: Conductor },
  { browser: Browser; drupalSite: DrupalSite; beforeAll: void }
>({
  beforeAll: [
    async ({ browser, drupalSite }, use, testInfo) => {
      await setupSite({ browser, drupalSite, baseURL: testInfo.project?.use?.baseURL || '' });
      await use();
    },
    { scope: 'worker', auto: true },
  ],
  canvas: [
    async ({ page }, use) => {
      const canvas = new Canvas({ page });
      await use(canvas);
    },
    { auto: true },
  ],
  conductor: [
    async ({ page, drupal, canvas }: { page: Page; drupal: Drupal; canvas: Canvas }, use) => {
      const conductor = new Conductor({ page, drupal, canvas });
      await use(conductor);
    },
    { auto: true },
  ],
});

export const parallelWorker = parallelWorkerBase.extend<
  { canvas: Canvas; conductor: Conductor },
  { browser: Browser; drupalSite: DrupalSite; beforeAll: void }
>({
  beforeAll: [
    async ({ browser, drupalSite }, use, testInfo) => {
      await setupSite({ browser, drupalSite, baseURL: testInfo.project?.use?.baseURL || '' });
      await use();
    },
    { scope: 'worker', auto: true },
  ],
  canvas: [
    async ({ page }, use) => {
      const canvas = new Canvas({ page });
      await use(canvas);
    },
    { auto: true },
  ],
  conductor: [
    async ({ page, drupal, canvas }: { page: Page; drupal: Drupal; canvas: Canvas }, use) => {
      const conductor = new Conductor({ page, drupal, canvas });
      await use(conductor);
    },
    { auto: true },
  ],
});
