{{ header }}
/**
 * App harness for server-pattern e2e tests
 *
 * This harness is spawned as a subprocess and runs the SUT app,
 * registering handlers per fixture. It loads all fixtures, creates
 * handlers that return expected responses, and serves on a configured port.
 */

{% for import_name in imports %}
import _pkg from '{{ import_name }}';
{% endfor %}
const { {{ app_class }}, ServerConfig } = _pkg;

// Load fixtures from the inline JSON payload.
const _FIXTURES = {{fixtures_json}};

// Create and configure the app
{% if constructor_method == ".new()" -%}
const app = {{ app_class }}.new();
{% else -%}
const app = new {{ app_class }}();
{% endif -%}

// Map HTTP method name to the corresponding app method
const httpMethodMap = {
  'GET': 'get',
  'POST': 'post',
  'PUT': 'put',
  'PATCH': 'patch',
  'DELETE': 'delete',
  'HEAD': 'head',
  'OPTIONS': 'options',
  'CONNECT': 'connect',
  'TRACE': 'trace',
};

// Register a handler for each fixture
for (const [fixtureId, fixture] of Object.entries(_FIXTURES)) {
  const http = fixture.http;
  if (!http) continue;

  const handler = http.handler || {};
  const route = handler.route || '/';
  const methodStr = (handler.method || 'GET').toUpperCase();
  const expected = http.expected_response || {};

  const expectedStatus = expected.status_code || 200;
  const expectedBody = expected.body;
  const expectedHeaders = expected.headers || {};

  // Map method string to the app method name
  const appMethodName = httpMethodMap[methodStr];
  if (!appMethodName) {
    console.warn(`Skipping fixture ${fixtureId}: unknown HTTP method ${methodStr}`);
    continue;
  }

  // Build handler function that returns the expected response
  const handlerFn = (request) => {
    return {
      status_code: expectedStatus,
      {{ response_body_field }}: expectedBody,
      headers: { ...expectedHeaders }
    };
  };

  // Register the handler at /fixtures/<fixture_id>{route}
  const fullRoute = `/fixtures/${fixtureId}${route}`;

  // Call the appropriate HTTP verb method on the app
  app[appMethodName](fullRoute, handlerFn);
}

// Configure and start the server
const config = new ServerConfig();
config.host = '{{ host }}';
config.port = {{ port }};
app.config(config);

console.log(`Harness listening on {{ host }}:{{ port }}`);
await app.{{ run_method }}();
