import { execSync } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

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

/**
 * Global setup for E2E tests.
 *
 * - Resets rate limiter to ensure tests start with clean state
 * - Token creation is handled per-browser in test files using beforeAll hooks
 */
async function globalSetup() {
	console.warn('🎭 E2E Global setup - tokens are created per browser project');

	// Reset rate limiter to prevent failed login tests from blocking other tests
	try {
		const projectRoot = join(__dirname, '../..');
		const composeFile = join(projectRoot, 'compose.yaml');

		// Use Symfony cache:pool:clear for more reliable cache clearing
		execSync(
			`docker compose -f "${composeFile}" exec -T php php bin/console cache:pool:clear cache.rate_limiter --env=dev 2>&1`,
			{ encoding: 'utf-8' }
		);
		console.warn('✅ Rate limiter cache cleared');
	} catch (error) {
		console.error('⚠️ Failed to reset rate limiter:', error);
	}
}

export default globalSetup;
