'use strict';

const test = require('node:test');
const assert = require('node:assert');
const { parsePositionAndLook, parseChat, parseJoinGame } = require('../src/bot/codec');

test('parsePositionAndLook: full payload', () => {
  const data = Buffer.alloc(33);
  data.writeDoubleLE(1.5, 0);
  data.writeDoubleLE(64.0, 8);
  data.writeDoubleLE(-3.25, 16);
  data.writeFloatLE(45.0, 24);
  data.writeFloatLE(15.0, 28);
  data[32] = 0;
  const r = parsePositionAndLook(data);
  assert.ok(r);
  assert.strictEqual(r.x, 1.5);
  assert.strictEqual(r.y, 64.0);
  assert.strictEqual(r.z, -3.25);
  assert.strictEqual(r.yaw, 45.0);
  assert.strictEqual(r.pitch, 15.0);
});

test('parsePositionAndLook: too short returns null', () => {
  const data = Buffer.alloc(10);
  assert.strictEqual(parsePositionAndLook(data), null);
});

test('parseChat: simple text', () => {
  const json = JSON.stringify({ text: 'Hello world' });
  const len = Buffer.byteLength(json);
  const data = Buffer.concat([
    Buffer.from([len]),
    Buffer.from(json, 'utf8'),
  ]);
  const r = parseChat(data);
  assert.strictEqual(r.text, 'Hello world');
});

test('parseChat: with translate', () => {
  const json = JSON.stringify({ translate: 'commands.register.success', with: ['alice'] });
  const data = Buffer.concat([
    Buffer.from([Buffer.byteLength(json)]),
    Buffer.from(json, 'utf8'),
  ]);
  const r = parseChat(data);
  assert.strictEqual(r.translate, 'commands.register.success');
  assert.ok(r.text.includes('commands.register.success'));
});

test('parseChat: strips color codes', () => {
  const json = JSON.stringify({ text: '§aGreen§r text' });
  const data = Buffer.concat([
    Buffer.from([Buffer.byteLength(json)]),
    Buffer.from(json, 'utf8'),
  ]);
  const r = parseChat(data);
  assert.strictEqual(r.text, 'Green text');
});

test('parseJoinGame: minimal', () => {
  const data = Buffer.alloc(10);
  data[0] = 1;
  data[1] = 0;
  data.writeInt32BE(0, 2);
  data[6] = 0;
  data[7] = 20;
  data[8] = 0;
  const r = parseJoinGame(data);
  assert.ok(r);
  assert.strictEqual(r.entityId, 1);
  assert.strictEqual(r.gamemode, 0);
  assert.strictEqual(r.dimension, 0);
  assert.strictEqual(r.maxPlayers, 20);
});
