/* eslint-disable no-console */
import { execSync } from 'node:child_process';
import path from 'node:path';

/**
 * Playwright globalSetup — runs once before all E2E tests.
 *
 * 1. Loads .env.test (if present) so DATABASE_URL points to the test DB.
 * 2. Runs Prisma migrations against the test database.
 * 3. Seeds the test database with sample data.
 */
export default async function globalSetup() {
  const root = path.resolve(__dirname, '..');
  const envTestPath = path.join(root, '.env.test');
  const isCI = !!process.env.CI;

  // In CI, env vars are already set by the workflow; locally, load .env.test
  if (!isCI) {
    const { config } = await import('dotenv');
    config({ path: envTestPath, override: true });
  }

  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) {
    throw new Error(
      'DATABASE_URL is not set. Create .env.test or set it in your environment.',
    );
  }

  // In CI, the workflow already runs migrations + seed before Playwright.
  // Skip to avoid duplicate work; only validate DATABASE_URL is set.
  if (isCI) {
    console.log('[E2E globalSetup] CI detected — skipping migrations/seed (handled by workflow).');
    return;
  }

  console.log('\n[E2E globalSetup] Preparing test database...');
  console.log(`[E2E globalSetup] DATABASE_URL = ${databaseUrl.replace(/\/\/.*@/, '//***@')}`);

  const execOpts = {
    cwd: root,
    stdio: 'inherit' as const,
    env: { ...process.env, DATABASE_URL: databaseUrl },
  };

  // Apply schema to test database.
  // Prisma 7 removed datasource.url from schema — the URL is in prisma.config.ts
  // which picks it up from DATABASE_URL env var set above.
  // For local dev, the test DB is typically set up manually or via pg_dump.
  console.log('[E2E globalSetup] Verifying test database schema...');
  try {
    execSync('npx prisma db push --accept-data-loss --config prisma/prisma.config.ts', execOpts);
  } catch (err) {
    console.warn('[E2E globalSetup] prisma db push failed (may be expected in Prisma 7):', (err as Error).message);
    console.log('[E2E globalSetup] Continuing — assuming test DB schema is already set up.');
  }

  // Seed database (upserts are idempotent)
  console.log('[E2E globalSetup] Seeding test database...');
  try {
    execSync('npx prisma db seed --config prisma/prisma.config.ts', execOpts);
  } catch (err) {
    console.warn('[E2E globalSetup] Seed failed (may be expected if Prisma 7 config changed):', (err as Error).message);
    console.log('[E2E globalSetup] Continuing — assuming test DB is already seeded.');
  }

  console.log('[E2E globalSetup] Test database ready.\n');
}
