import nodemailer from 'nodemailer';
import { hasTransport, hasTransportOptions } from '../config/types.js';
import { InvalidConfiguration } from '../errors/index.js';
import mockHandler from './mockHandler.js';
async function handleTransport(transport, email, logger) {
    try {
        await transport.verify();
    } catch (err) {
        logger.error(`There is an error with the email configuration you have provided. ${err}`);
    }
    return {
        ...email,
        transport
    };
}
const ensureConfigHasFrom = (emailConfig)=>{
    if (!emailConfig?.fromName || !emailConfig?.fromAddress) {
        throw new InvalidConfiguration('Email fromName and fromAddress must be configured when transport is configured');
    }
};
const handleMockAccount = async (emailConfig, logger)=>{
    let mockAccount;
    try {
        mockAccount = await mockHandler(emailConfig);
        const { account: { pass, user, web } } = mockAccount;
        if (emailConfig?.logMockCredentials) {
            logger.info('E-mail configured with mock configuration');
            logger.info(`Log into mock email provider at ${web}`);
            logger.info(`Mock email account username: ${user}`);
            logger.info(`Mock email account password: ${pass}`);
        }
    } catch (err) {
        logger.error({
            err,
            msg: 'There was a problem setting up the mock email handler'
        });
    }
    return mockAccount;
};
export default async function buildEmail(emailConfig, logger) {
    if (!emailConfig) {
        return handleMockAccount(emailConfig, logger);
    }
    if (hasTransport(emailConfig) && emailConfig.transport) {
        ensureConfigHasFrom(emailConfig);
        const email = {
            ...emailConfig
        };
        const { transport } = emailConfig;
        return handleTransport(transport, email, logger);
    }
    if (hasTransportOptions(emailConfig) && emailConfig.transportOptions) {
        ensureConfigHasFrom(emailConfig);
        const email = {
            ...emailConfig
        };
        const transport = nodemailer.createTransport(emailConfig.transportOptions);
        return handleTransport(transport, email, logger);
    }
    return handleMockAccount(emailConfig, logger);
}

//# sourceMappingURL=build.js.map