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

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

const TENANT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';

/**
 * Global setup for E2E tests.
 *
 * - Cleans transactional data that could cause FK constraint failures
 *   (each test file handles its own specific cleanup in beforeAll/beforeEach)
 * - Resets rate limiter cache
 * - 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');

	const projectRoot = join(__dirname, '../..');
	const composeFile = join(projectRoot, 'compose.yaml');

	function runSql(sql: string) {
		execSync(
			`docker compose -f "${composeFile}" exec -T php php bin/console dbal:run-sql "${sql}" 2>&1`,
			{ encoding: 'utf-8' }
		);
	}

	// Clean grade data (Story 6.2) to prevent FK constraint failures
	// when other tests try to DELETE FROM evaluations
	try {
		runSql(`DELETE FROM grade_events WHERE grade_id IN (SELECT id FROM grades WHERE tenant_id = '${TENANT_ID}')`);
		runSql(`DELETE FROM grades WHERE tenant_id = '${TENANT_ID}'`);
		console.warn('✅ Grade data cleaned');
	} catch {
		// Tables may not exist yet
	}

	// Reset rate limiter to prevent failed login tests from blocking other tests
	try {
		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;
