/**
 * Setup file - Runs before EACH test file
 * Initialize server singleton here
 */

// Ensure test environment variables are set before any application modules load
process.env.NODE_ENV = process.env.NODE_ENV || 'test';
process.env.PORT = process.env.PORT || 5001;
process.env.ADMIN_SESSION_SECRET = process.env.ADMIN_SESSION_SECRET || 'test-session-secret';

const Server = require('../src/server');

// Singleton pattern - initialize only once
let serverInstance = null;
let app = null;

async function initializeTestServer() {
  if (!app) {
    console.log('🔧 Initializing test server (one-time)...');
    
    serverInstance = new Server(5001);
    app = await serverInstance.initializeApp();
    
    global.__TEST_SERVER__ = serverInstance;
    global.__TEST_APP__ = app;
    
    console.log('✅ Test server ready');
  }
  return app;
}

// Initialize before all tests
beforeAll(async () => {
  await initializeTestServer();
});

// Test timeout
jest.setTimeout(10000);

// Suppress logs during tests
global.console = {
  ...console,
  log: jest.fn(),
  info: jest.fn(),
  debug: jest.fn(),
  error: console.error,
  warn: console.warn,
};
