function splitFields(segment) {
  return segment.split('|');
}

function formatHl7Timestamp(value) {
  if (!value) return new Date().toISOString();
  const year = value.slice(0, 4);
  const month = value.slice(4, 6) || '01';
  const day = value.slice(6, 8) || '01';
  const hour = value.slice(8, 10) || '00';
  const minute = value.slice(10, 12) || '00';
  const second = value.slice(12, 14) || '00';
  if (!year || !month || !day) {
    return new Date().toISOString();
  }
  return `${year}-${month}-${day}T${hour}:${minute}:${second}Z`;
}

async function parseHl7(message) {
  const payload = typeof message === 'string' ? message.trim() : '';
  if (!payload) {
    throw new Error('empty HL7 payload');
  }

  const segments = payload.split(/\r?\n/).filter(Boolean);
  const msh = segments.find((line) => line.startsWith('MSH'));
  const obr = segments.find((line) => line.startsWith('OBR'));
  const obxSegments = segments.filter((line) => line.startsWith('OBX'));

  const mshFields = msh ? splitFields(msh) : [];
  const obrFields = obr ? splitFields(obr) : [];

  const instrument_id = (obrFields[2] || '').split('^')[0] || 'hl7-instrument';
  const sample_id = (obrFields[3] || obrFields[2] || '').split('^')[0] || `${instrument_id}-sample`;
  const result_time = formatHl7Timestamp(obrFields[7] || mshFields[6] || '');
  if (!obxSegments.length) {
    throw new Error('no OBX segments in HL7 payload');
  }

  const results = obxSegments.map((segment) => {
    const fields = splitFields(segment);
    return {
      test_code: (fields[3] || 'UNKNOWN').split('^')[0],
      value: fields[5] || '0',
      unit: fields[6] || undefined,
      flag: fields[8] || undefined,
      meta: {
        observation_id: fields[3]
      }
    };
  });

  const canonical = {
    instrument_id: instrument_id.trim(),
    sample_id: sample_id.trim(),
    result_time,
    results,
    meta: {
      source_protocol: 'HL7',
      message_id: mshFields[9] || undefined,
      connector: 'hl7-tcp',
      obx_count: obxSegments.length
    }
  };

  return canonical;
}

module.exports = { parse: parseHl7 };
