import { defineConfig, devices } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default defineConfig({
	testDir: './e2e',

	// Auto-starts the SvelteKit dev server before E2E tests.
	// Reuses the existing server if already running (e.g. during active development).
	// The backend + DB + MinIO must be started separately (see README or CI workflow).
	webServer: {
		command: 'npm run dev -- --port 3000',
		// Use the E2E_BASE_URL so that a pre-running server (e.g. the docker dev server
		// on port 5173 during local development) is detected and reused without starting
		// a new one. In CI the default is localhost:3000 where a fresh server is started.
		url: process.env.E2E_BASE_URL ?? 'http://localhost:3000',
		reuseExistingServer: true,
		timeout: 120_000
	},
	fullyParallel: false, // tests share auth state → run sequentially within a worker
	retries: process.env.CI ? 2 : 0,
	workers: 1,

	use: {
		baseURL: process.env.E2E_BASE_URL ?? 'http://localhost:3000',
		locale: 'de-DE', // ensures Accept-Language: de is sent so locale detection defaults to German
		reducedMotion: 'reduce', // prevents SMIL/CSS animations from flaking tests
		screenshot: 'on', // always capture screenshots
		video: 'retain-on-failure',
		trace: 'retain-on-failure'
	},

	projects: [
		// 1. Auth setup: logs in and saves the session cookie to disk
		{
			name: 'setup',
			testMatch: /auth\.setup\.ts/
		},
		// 2. All E2E tests, re-using the stored session
		{
			name: 'chromium',
			use: {
				...devices['Desktop Chrome'],
				storageState: path.join(__dirname, 'e2e/.auth/user.json')
			},
			dependencies: ['setup']
		}
	],

	outputDir: 'test-results/e2e'
});
