const request = require('supertest');

/**
 * Get supertest request instance
 * Uses globally initialized server from globalSetup.js
 */
let cachedAgent = null;

function getApp() {
  const app = global.__TEST_APP__;
  if (!app) {
    throw new Error(
      'Test server not initialized. This should be handled by globalSetup.js automatically.'
    );
  }
  return app;
}

function getRequest() {
  return request(getApp());
}

function getAgent() {
  if (!cachedAgent) {
    cachedAgent = request.agent(getApp());
  }
  return cachedAgent;
}

/**
 * Legacy compatibility - these are now no-ops
 * Server is initialized globally
 */
async function setupTestServer() {
  return { 
    app: global.__TEST_APP__, 
    serverInstance: global.__TEST_SERVER__ 
  };
}

async function teardownTestServer() {
  // No-op - cleanup happens in globalTeardown.js
}

module.exports = {
  setupTestServer,
  teardownTestServer,
  getRequest,
  getAgent
};
