import type { PlaywrightTestConfig } from '@playwright/test';

const baseURL = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:4173';
const useExternalServer = !!process.env.PLAYWRIGHT_BASE_URL;

const config: PlaywrightTestConfig = {
	// Always run globalSetup to seed test tokens
	// If backend is not running, tests requiring tokens will be skipped gracefully
	globalSetup: './e2e/global-setup.ts',
	webServer: useExternalServer
		? undefined
		: {
				command: 'pnpm run build && pnpm run preview',
				port: 4173,
				reuseExistingServer: !process.env.CI
			},
	testDir: 'e2e',
	testMatch: /(.+\.)?(test|spec)\.[jt]s/,
	// Run browsers sequentially in CI to avoid race conditions with shared database
	// Classes tests use mode: 'serial' which only works within a single worker
	fullyParallel: !process.env.CI,
	// Use 1 worker in CI to ensure no parallel execution across different browser projects
	workers: process.env.CI ? 1 : undefined,
	use: {
		baseURL,
		trace: 'on-first-retry',
		screenshot: 'only-on-failure',
		video: 'retain-on-failure'
	},
	retries: process.env.CI ? 2 : 0,
	reporter: process.env.CI ? 'github' : 'html',
	projects: [
		{
			name: 'chromium',
			use: {
				browserName: 'chromium'
			}
		},
		{
			name: 'firefox',
			use: {
				browserName: 'firefox'
			}
		},
		{
			name: 'webkit',
			use: {
				browserName: 'webkit'
			}
		}
	]
};

export default config;
