/* eslint-disable @typescript-eslint/no-explicit-any */
import { expect } from 'chai';
import { Buffer } from 'buffer';
import 'mocha';
import bs58 from 'bs58';

import * as walletDev from '../src';
import * as walletProduction from '../lib/index.commonjs';

//
let SPLWallet: any;
const env = process.env.NODE_ENV;
if (env === 'production') {
  SPLWallet = walletProduction.SPLWallet;
} else {
  SPLWallet = walletDev.SPLWallet;
}

describe(`Keypair on ${env} environment`, () => {
  it('generate new keypair', () => {
    const keypair = SPLWallet.generateWallet();
    expect(keypair.signer.secretKey).to.have.length(64);
  });

  it('create keypair from secret key', () => {
    const secretKey = Buffer.from(
      'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIg==',
      'base64'
    );
    const keypair = SPLWallet.fromSecretKey(secretKey);
    expect(keypair.signer.publicKey.toBase58()).to.eq(
      '2q7pyhPwAwZ3QMfZrnAbDhnh9mDUqycszcpf86VgQxhF'
    );
  });

  it('create keypair from string secret key', () => {
    const keypair = SPLWallet.generateWallet();
    const priveteKey = keypair.signer.secretKey;
    const privateString = bs58.encode(priveteKey);
    const newKeyPair = SPLWallet.fromStringSecretKey(privateString);

    expect(newKeyPair.address).to.eq(keypair.address);
  });

  it('creating keypair from invalid secret key throws error', () => {
    const secretKey = Buffer.from(
      'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIG==',
      'base64'
    );
    expect(() => {
      SPLWallet.fromSecretKey(secretKey);
    }).to.throw('provided secretKey is invalid');
  });

  it('generate keypair from random seed', () => {
    const keypair = SPLWallet.fromSeed(Uint8Array.from(Array(32).fill(8)));
    expect(keypair.signer.publicKey.toBase58()).to.eq(
      '2KW2XRd9kwqet15Aha2oK3tYvd3nWbTFH1MBiRAv1BE1'
    );
  });

  it('generate keypair from Mnemonic', async () => {
    const mnemonic =
      'snake stairs easy edge anxiety glimpse unlock gun jelly carry flight mobile';
    const keypair = await SPLWallet.fromMnemonic(mnemonic);

    expect(keypair.address).to.eq(
      '7cj9CKJke1sX5CsDKWqFyzBZo7YGzWzW1r5aNDk2Wbqi'
    );
  });
});
