import { chromium, type FullConfig } from '@playwright/test';
import { execSync } from 'node:child_process';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';

const STORAGE_PATH = '.auth/admin.json';

export default async function globalSetup(config: FullConfig): Promise<void> {
  const baseURL =
    config.projects[0]?.use?.baseURL ?? 'https://flowdrop.ddev.site';

  // Clean up any leftover sessions for the test workflows so each run starts
  // from a known empty state. Sessions accumulate quickly during iteration
  // and crowd the "Switch session" dropdown out of the viewport.
  const cleanupPhp = `\\$ids = \\Drupal::entityTypeManager()` +
    `->getStorage('flowdrop_session')->getQuery()->accessCheck(FALSE)` +
    `->condition('workflow_id', ['e2e_calculator_user', 'e2e_calculator', 'e2e_ask_confirmation'], 'IN')` +
    `->execute(); ` +
    `if (\\$ids) { ` +
    `\\$storage = \\Drupal::entityTypeManager()->getStorage('flowdrop_session'); ` +
    `\\$storage->delete(\\$storage->loadMultiple(\\$ids)); ` +
    `}`;
  execSync(`ddev drush ev "${cleanupPhp}"`, { encoding: 'utf8' });

  // Mint a one-time login link for uid=1 via drush (no password storage,
  // mirrors how Nightwatch authenticates in Drupal core).
  const loginUrl = execSync(
    `ddev drush uli --no-browser --uri=${baseURL} --uid=1`,
    { encoding: 'utf8' },
  ).trim();

  if (!loginUrl.startsWith('http')) {
    throw new Error(`drush uli returned unexpected output: ${loginUrl}`);
  }

  mkdirSync(dirname(STORAGE_PATH), { recursive: true });

  const browser = await chromium.launch();
  const context = await browser.newContext({ ignoreHTTPSErrors: true });
  const page = await context.newPage();
  await page.goto(loginUrl);
  // After hitting the uli link Drupal redirects to /user/<uid>/edit; just
  // wait for any post-login page to render.
  await page.waitForLoadState('networkidle');
  await context.storageState({ path: STORAGE_PATH });
  await browser.close();
}
