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

// Define the HashMap type and values
const HashMap = {
  SHA256withRSA: 'SHA256withRSA',
  SHA1withRSA: 'SHA1withRSA',
};

const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n';
const PEM_END = '\n-----END PRIVATE KEY-----';

export const sign = (params: Record<string, any>, privateKey: string): string => {
  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 str = SignUtil.rsaSign(parseStr, privateKey, HashMap.SHA1withRSA);
  console.log('sign', str);

  return str;
};

const SignUtil = {
  rsaSign: function (content: string, privateKey: string, hash: string): string {
    const _privateKey = this._formatKey(privateKey);
    console.log('parseStr', _privateKey);

    // Type assertion to handle the private key type issue
    const signature = new KJUR.crypto.Signature({
      alg: hash,
      prvkeypem: _privateKey,
    } as any); // <-- Type assertion to bypass type checking

    signature.updateString(content);
    const signData = signature.sign();

    return hextob64(signData);
  },

  _formatKey: function (key: string): string {
    if (!key.startsWith(PEM_BEGIN)) {
      key = PEM_BEGIN + key;
    }
    if (!key.endsWith(PEM_END)) {
      key = key + PEM_END;
    }
    return key;
  },
};

export default SignUtil;
