const net = require('net');
const config = require('../../config/default');
const logger = require('../utils/logger');

function createHl7TcpConnector() {
  let server;
  let messageHandler = async () => {};
  let errorHandler = (err) => logger.error({ err }, 'hl7 connector error');

  const connections = new Set();

  function handleData(socket, chunk) {
    const payload = chunk.toString('utf8').trim();
    if (!payload) return;
    messageHandler(payload).catch(errorHandler);
  }

  function attach(socket) {
    connections.add(socket);
    socket.on('data', (chunk) => handleData(socket, chunk));
    socket.on('error', (err) => errorHandler(err));
    socket.on('close', () => connections.delete(socket));
  }

  return {
    name: () => 'hl7-tcp',
    type: () => 'hl7-tcp',
    async start() {
      server = net.createServer(attach);
      return new Promise((resolve, reject) => {
        server.listen(config.connectors.hl7TcpPort, () => {
          logger.info({ port: config.connectors.hl7TcpPort }, 'hl7 tcp connector listening');
          resolve();
        });
        server.on('error', (err) => {
          errorHandler(err);
          reject(err);
        });
      });
    },
    async stop() {
      for (const socket of connections) {
        socket.destroy();
      }
      if (!server) return;
      return new Promise((resolve, reject) => {
        server.close((err) => {
          if (err) return reject(err);
          resolve();
        });
      });
    },
    health() {
      return { status: server ? 'up' : 'down', port: config.connectors.hl7TcpPort }; 
    },
    onMessage(handler) {
      messageHandler = handler;
    },
    onError(handler) {
      errorHandler = handler;
    }
  };
}

module.exports = { createHl7TcpConnector };
