import * as plugins from '../../../plugins.js';

/**
 * Generate a self-signed fallback certificate (CN=SmartProxy Default Certificate, SAN=*).
 * Used as the '*' wildcard fallback so TLS handshakes never reset due to missing certs.
 */
export function generateDefaultCertificate(): { cert: string; key: string } {
  const forge = plugins.smartcrypto.nodeForge;

  // Generate 2048-bit RSA keypair
  const keypair = forge.pki.rsa.generateKeyPair({ bits: 2048 });

  // Create self-signed X.509 certificate
  const cert = forge.pki.createCertificate();
  cert.publicKey = keypair.publicKey;
  cert.serialNumber = '01';
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

  const attrs = [{ name: 'commonName', value: 'SmartProxy Default Certificate' }];
  cert.setSubject(attrs);
  cert.setIssuer(attrs);

  // Add wildcard SAN
  cert.setExtensions([
    { name: 'subjectAltName', altNames: [{ type: 2 /* DNS */, value: '*' }] },
  ]);

  cert.sign(keypair.privateKey, forge.md.sha256.create());

  return {
    cert: forge.pki.certificateToPem(cert),
    key: forge.pki.privateKeyToPem(keypair.privateKey),
  };
}
