import { endpoints } from './endpoints/index.js';
import { normalizePath, readBody, sendJson } from './http.js';

function buildConfig(config = {}) {
  return {
    authToken: config.authToken || process.env.AUTH_TOKEN || 'df40ad2067954646abb0499548a52241',
    certificateFingerprint:
      config.certificateFingerprint ||
      process.env.CERTIFICATE_FINGERPRINT ||
      'BC2114CF407A42724BEEF417960F76DCBF9DE879',
    certificateSerialNumber:
      config.certificateSerialNumber ||
      process.env.CERTIFICATE_SERIAL_NUMBER ||
      '00BFC8BEACDB981B165210EF111CB9D3',
    serverFingerprint:
      config.serverFingerprint ||
      process.env.SERVER_FINGERPRINT ||
      '39-6D-BD-DE-F3-5C-5A-EA-C2-19-CF-EB-A7-A9-58-2F-20-3F-20-F7-3D-E6-CA-8E-AE-FD-28-30-37-A6-45-AE',
    mandantId: config.mandantId || process.env.MANDANT_ID || '1',
    mandantName: config.mandantName || process.env.MANDANT_NAME || 'eB-Standard',
    mandantDatabase: config.mandantDatabase || process.env.MANDANT_DATABASE || 'eazybusiness',
  };
}

export function createJtlPosServer(pairingStore, config = {}) {
  const resolvedConfig = buildConfig(config);
  const routes = new Map(endpoints.map((endpoint) => [`${endpoint.method} ${endpoint.path}`, endpoint]));

  async function handle(req, res) {
    const url = new URL(req.url, 'https://localhost');
    const pathname = normalizePath(url.pathname);
    const routeKey = `${req.method} ${pathname}`;
    const endpoint = routes.get(routeKey);

    if (endpoint) {
      return await endpoint.handle(req, res, { url, pairingStore, config: resolvedConfig });
    }

    return sendJson(res, 404, {
      Message: `No HTTP resource was found that matches the request URI '${url}'.`,
    });
  }

  return async function requestListener(req, res) {
    req.rawBody = await readBody(req);
    try {
      await handle(req, res);
    } catch (err) {
      sendJson(res, 500, { Message: err.message });
    }
  };
}
