const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const CERT_PATH = path.join(__dirname, '../root.crt');
const OUTPUT_PATH = path.join(__dirname, '../cert-info.json');

function extractCertInfo() {
  try {
    console.log('Extracting certificate information from:', CERT_PATH);

    // Extract SHA-256 fingerprint
    const fingerprint = execSync(`openssl x509 -in "${CERT_PATH}" -noout -fingerprint -sha256`)
      .toString()
      .trim()
      .split('=')[1];

    // Extract validity dates
    const dates = execSync(`openssl x509 -in "${CERT_PATH}" -noout -dates`).toString();
    const notBefore = dates.match(/notBefore=(.*)/)[1].trim();
    const notAfter = dates.match(/notAfter=(.*)/)[1].trim();

    // Extract subject
    const subject = execSync(`openssl x509 -in "${CERT_PATH}" -noout -subject`)
      .toString()
      .trim()
      .split('CN = ')[1] || execSync(`openssl x509 -in "${CERT_PATH}" -noout -subject`)
      .toString()
      .trim()
      .split('CN=')[1];

    // Extract serial number
    const serialNumber = execSync(`openssl x509 -in "${CERT_PATH}" -noout -serial`)
      .toString()
      .trim()
      .split('=')[1];

    // Calculate days until expiration
    const expirationDate = new Date(notAfter);
    const today = new Date();
    const daysUntilExpiration = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));

    const certInfo = {
      name: subject,
      fingerprint: fingerprint,
      validFrom: notBefore,
      validUntil: notAfter,
      daysUntilExpiration: daysUntilExpiration,
      algorithm: 'ECDSA P-256 with SHA-256',
      issuer: subject, // Self-signed root CA
      serialNumber: serialNumber,
      generatedAt: new Date().toISOString()
    };

    fs.writeFileSync(OUTPUT_PATH, JSON.stringify(certInfo, null, 2));
    console.log('✓ Certificate information extracted successfully!');
    console.log('  Output:', OUTPUT_PATH);
    console.log('  Name:', certInfo.name);
    console.log('  Fingerprint:', certInfo.fingerprint);
    console.log('  Valid until:', certInfo.validUntil);
    console.log('  Days until expiration:', certInfo.daysUntilExpiration);

    return certInfo;
  } catch (error) {
    console.error('Error extracting certificate information:', error.message);
    process.exit(1);
  }
}

// Run if called directly
if (require.main === module) {
  extractCertInfo();
}

module.exports = { extractCertInfo };
