import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import {
  createWallet,
  importMnemonic,
  importPrivateKey,
  payloadHash,
  signPayload,
} from '../public/wallet_crypto.mjs';

const require = createRequire(import.meta.url);
const { payloadHash: serverPayloadHash, verifySignature } = require('../src/lib/wallet');

const payload = {
  type: 'NATIVE_WALLET_SAMPLE',
  chain_id: 'mazexchain-local',
  nonce: 1729,
  values: [1, 2, 3],
};

const wallet = await createWallet();
const fromMnemonic = await importMnemonic(wallet.mnemonic);
const fromPrivateKey = await importPrivateKey(wallet.private_key);
const signed = await signPayload(wallet, payload);
const verified = verifySignature({
  publicKey: signed.public_key,
  address: signed.address,
  payload: signed.payload,
  signature: signed.signature,
});

assert.equal(fromMnemonic.address, wallet.address, 'Mnemonic import must restore the same address');
assert.equal(fromPrivateKey.address, wallet.address, 'Private key import must restore the same address');
assert.equal(await payloadHash(payload), serverPayloadHash(payload), 'Client payload hash must match server payload hash');
assert.equal(verified.ok, true, 'Server must verify browser-side Ed25519 signature');

console.log({
  module: 'native_wallet_crypto',
  ok: true,
  address: wallet.address,
  payload_hash: signed.payload_hash,
});
