import md5 from 'md5';
import { KJUR, b64tohex, hextob64 } from 'jsrsasign';

const PUB_PEM_BEGIN = '-----BEGIN PUBLIC KEY-----\n';
const PUB_PEM_END = '\n-----END PUBLIC KEY-----\n';

const HashMap = {
  SHA256withRSA: 'SHA256withRSA',
  SHA1withRSA: 'SHA1withRSA',
};

export class VerifyUtil {
  static rsaVerify(content: string, signature: string, publicKey: string, hash: string): boolean {
    const _publicKey = this._formatKey(publicKey);

    const sig = new KJUR.crypto.Signature({ alg: hash });
    sig.init(_publicKey);
    sig.updateString(content);
    return sig.verify(b64tohex(signature));
  }

  static verify(params: Record<string, any>, signature: string, publicKey: string): boolean {
    let parseStr = Object.keys(params)
      .sort()
      .filter((item) => params[item])
      .map((item) => `${item}=${params[item]}`)
      .join('&');

    console.log('parseStr', parseStr);

    parseStr = md5(parseStr).toUpperCase();
    console.log('MD5', parseStr);

    const isValid = this.rsaVerify(parseStr, signature, publicKey, HashMap.SHA1withRSA);
    console.log('isValid', isValid);

    return isValid;
  }

  private static _formatKey(key: string): string {
    if (!key.startsWith(PUB_PEM_BEGIN)) {
      key = PUB_PEM_BEGIN + key;
    }
    if (!key.endsWith(PUB_PEM_END)) {
      key = key + PUB_PEM_END;
    }
    return key;
  }
}
