const crc16X25 = (payload: Buffer) => {
  let crc = 0xffff;

  for (const byte of payload) {
    crc ^= byte;
    for (let index = 0; index < 8; index += 1) {
      crc = (crc & 1) === 1 ? (crc >> 1) ^ 0x8408 : crc >> 1;
    }
  }

  return (~crc) & 0xffff;
};

export const encodeGt06Ack = (protocolNumber: number, serial: Buffer) => {
  const body = Buffer.from([0x05, protocolNumber, serial[0] ?? 0x00, serial[1] ?? 0x00]);
  const crc = crc16X25(body);

  return Buffer.from([
    0x78,
    0x78,
    ...body,
    (crc >> 8) & 0xff,
    crc & 0xff,
    0x0d,
    0x0a,
  ]);
};
