import nodemailer from 'nodemailer';

import { config, logger } from '@opengis/fastify-table/utils.js';

/**
 * Надсилає поваідомлення на пошту
 *
 * @type function
 * @alias sendEmail
 * @summary Функція здійснює розсилку по email
 */

export default async function sendEmail({
  to, from, subject, html, attachments,
}) {
  if (!to?.length) {
    throw new Error('empty to list');
  }

  const { mailSetting = {} } = config;

  /*= == check service and setting === */
  if (!mailSetting.service) {
    logger.file('notification/warn', { to, from, message: 'service is not defined in config' });
    return;
  }

  Object.assign(mailSetting, { rejectUnauthorized: false });

  if (mailSetting.port === 465) {
    Object.assign(mailSetting, { secure: true });
  }

  const transport = nodemailer.createTransport(mailSetting);

  const result = await transport.sendMail({
    from: from || mailSetting.from, to, subject, html, attachments,
  });
  return result;
}
