import * as forge from 'node-forge';
// import { RSA } from 'react-native-rsa-native';

export async function generateKeyPairMobile() {
  // try {
  //   const keyPair: any = await RSA.generate();
  //   return {
  //     privateKey: keyPair.private,
  //     publicKey: keyPair.public,
  //   };
  // } catch (error) {
  //   console.error('Error generating key pair:', error);
  //   return false;
  // }
  const keypair = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });

  return {
    publicKey: forge.pki.publicKeyToPem(keypair.publicKey),
    privateKey: forge.pki.privateKeyToPem(keypair.privateKey),
  };
}

// Función auxiliar para obtener el OID correspondiente a cada atributo
function getOIDByShortName(shortName: 'C' | 'L' | 'ST' | 'CN' | 'E'): string {
  const oids = {
    C: '2.5.4.6', // País
    L: '2.5.4.7', // Localidad
    ST: '2.5.4.8', // Estado
    CN: '2.5.4.3', // Nombre común
    E: '1.2.840.113549.1.9.1', // Correo electrónico
  };

  return oids[shortName] || '';
}

export async function generateCertificateMobile(
  keyPair: { publicKey: string; privateKey: string }
  // userData: any
) {
  const { publicKey, privateKey } = keyPair;

  const csr: any = forge.pki.createCertificationRequest();

  csr.publicKey = forge.pki.publicKeyFromPem(publicKey);
  csr.serialNumber = '01';
  csr.version = 0;
  csr.subjectPublicKeyInfo = forge.pki.publicKeyToAsn1(
    forge.pki.publicKeyFromPem(publicKey)
  );

  csr.setSubject([
    {
      type: getOIDByShortName('C'),
      name: 'C',
      value: 'VE',
    },
    // {
    //   type: getOIDByShortName('E'),
    //   name: 'E',
    //   value: userData.email, // E (Email)
    // },
  ]);

  csr.sign(forge.pki.privateKeyFromPem(privateKey), forge.md.sha512.create());

  const asn1Cert = forge.pki.certificationRequestToAsn1(csr);

  const berBytes = forge.asn1.toDer(asn1Cert).getBytes();

  const berBase64 = forge.util.encode64(berBytes);

  return { csr: berBase64, subject: csr.subject };
}
