/**
 * Playwright Global Setup
 *
 * Runs once before all E2E tests. Responsible for:
 * 1. Seeding the database with deterministic E2E test fixtures (via artisan e2e:seed --reset)
 * 2. Authenticating the test user and saving the browser storage state to disk
 *
 * The saved auth state is consumed by the `storageState` fixture in tests/e2e/fixtures/auth.ts,
 * so individual tests start already logged in without repeating the login flow.
 */

import { chromium, type FullConfig } from '@playwright/test';
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const AUTH_STATE_PATH = path.join(__dirname, '.auth-state.json');
const SEED_DATA_PATH = path.join(__dirname, '.seed-data.json');

export default async function globalSetup(config: FullConfig): Promise<void> {
  // ── 1. Seed the database ────────────────────────────────────────────────────
  console.log('[E2E Setup] Seeding test database...');

  let seedOutput: string;
  try {
    seedOutput = execSync('php artisan e2e:seed --reset 2>&1', {
      cwd: process.cwd(),
      encoding: 'utf8',
      timeout: 60_000,
    });
  } catch (err) {
    console.error('[E2E Setup] artisan e2e:seed failed:', err);
    throw err;
  }

  // Extract the JSON marker written by E2ESeedCommand (last line starting with '{')
  const jsonLine = seedOutput
    .trim()
    .split('\n')
    .reverse()
    .find((line) => line.trim().startsWith('{'));

  if (!jsonLine) {
    throw new Error(
      `[E2E Setup] Could not find JSON output from e2e:seed. Command output:\n${seedOutput}`,
    );
  }

  const seedData = JSON.parse(jsonLine) as {
    userId: number;
    siteId: number;
    siteName: string;
    analysisRunId: number;
    recommendationId: number;
    aiDraftId: number;
    wpPostId: number;
  };
  fs.writeFileSync(SEED_DATA_PATH, JSON.stringify(seedData, null, 2));
  console.log('[E2E Setup] Seed data written to', SEED_DATA_PATH);
  console.log('[E2E Setup] Seed data:', seedData);

  // ── 2. Authenticate the test user and save session ─────────────────────────
  const baseURL =
    (config.projects[0]?.use?.baseURL as string | undefined) ?? 'http://localhost:8000';

  console.log('[E2E Setup] Authenticating test user at', baseURL);

  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  try {
    await page.goto(`${baseURL}/login`, { waitUntil: 'domcontentloaded' });
    await page.locator('input[name="email"]').fill('e2e-test@rankwiz.test');
    await page.locator('input[name="password"]').fill('E2ePassword123!');
    await page.locator('button[type="submit"]').click();

    // Dashboard redirects — wait for any page after login
    await page.waitForURL(/\/(dashboard|sites|onboarding)/, { timeout: 15_000 });

    await context.storageState({ path: AUTH_STATE_PATH });
    console.log('[E2E Setup] Auth state saved to', AUTH_STATE_PATH);
  } finally {
    await browser.close();
  }
}
