"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTlsCertificateSelector = getTlsCertificateSelector;
const errors_1 = require("@mongosh/errors");
const module_1 = require("module");
async function getTlsCertificateSelector(selector) {
    if (!selector) {
        return;
    }
    const exportCertificateAndPrivateKey = getCertificateExporter();
    if (!exportCertificateAndPrivateKey) {
        throw new errors_1.MongoshUnimplementedError('--tlsCertificateSelector is not supported on this platform');
    }
    const match = /^(?<key>\w+)=(?<value>.+)/.exec(selector);
    if (!match || !['subject', 'thumbprint'].includes(match.groups?.key ?? '')) {
        throw new errors_1.MongoshInvalidInputError('--tlsCertificateSelector needs to include subject or thumbprint');
    }
    const { key, value } = match.groups ?? {};
    const search = key === 'subject'
        ? { subject: value }
        : { thumbprint: Buffer.from(value, 'hex') };
    try {
        const { passphrase, pfx } = await exportCertificateAndPrivateKey(search);
        return { passphrase, pfx };
    }
    catch (err) {
        throw new errors_1.MongoshInvalidInputError(`Could not resolve certificate specification '${selector}': ${err?.message}`);
    }
}
function getCertificateExporter() {
    if (process.env.TEST_OS_EXPORT_CERTIFICATE_AND_KEY_PATH) {
        return (0, module_1.createRequire)(__filename)(process.env.TEST_OS_EXPORT_CERTIFICATE_AND_KEY_PATH);
    }
    try {
        switch (process.platform) {
            case 'win32':
                return require('win-export-certificate-and-key')
                    .exportCertificateAndPrivateKeyAsync;
            case 'darwin':
                return require('macos-export-certificate-and-key')
                    .exportCertificateAndPrivateKeyAsync;
            default:
                return undefined;
        }
    }
    catch {
    }
    return undefined;
}
//# sourceMappingURL=tls-certificate-selector.js.map