import { TLSSocket } from 'node:tls';

export const getCertificate = async ({ console, fs, cert, p12, password }) => {
    if (!cert && !p12) {
        const err = new Error('Path to certificate or certificate bundle is missing');
        throw err;
    }
    if (p12 && !password) {
        const err = new Error('Password to open certificate bundle is missing');
        throw err;
    }
    let socket;
    if (cert) {
        console.debug(`Reading certificate from file: ${cert}`);
        const certText = await fs.readFile(cert);
        console.debug('Parsing certificate');
        socket = new TLSSocket(null, { cert: certText });
    } else {
        console.debug(`Reading certificate bundle from file: ${p12}`);
        const p12Text = await fs.readFile(p12);
        console.debug('Parsing certificate bundle');
        socket = new TLSSocket(null, { pfx: p12Text, passphrase: password });
    }
    const x509Cert = socket.getCertificate();
    socket.destroy();
    console.debug('Parsed certificate:', x509Cert);
    return x509Cert;
};
